简体   繁体   中英

How to filter an array from all elements of another array in React

I get the data from API like this.

data1 = [
    {id:1, name:'Ant'},
    {id:2, name:'Bird'},
    {id:4, name:'Dog'},
    {id:5, name:'Egg'}
];

data2 = [
    {id:2, name:'Bird'},
    {id:3, name:'Cat'},
    {id:4, name:'Dog'},
    {id:6, name:'Fish'}
];

and I coding to get the data of 2 arrays by using filter and map array but I don't know how to filter 'data 2' in 'data 1' to get the result (check id if it's the same won't show in the result)

My expect result is

result = [
    {id:1, name:'Ant'},
    {id:3, name:'Cat'},
    {id:5, name:'Egg'},
    {id:6, name:'Fish'}
];

This is my code.

let getExistdata = {...this.props.data1.data}

let getExistedDataId = this.props.animal.data.map((existData)=> {
  let animalList= this.props.data2.data.filter(animal=> (animal.id !== this.props.id) && (animal.id !== existData.id) );
  console.log(animalList);

  return animalList;

});

Thank you

One way is to filter both arrays and concat them together:

 data1 = [ {id:1, name:'Ant'}, {id:2, name:'Bird'}, ]; data2 = [ {id:2, name:'Bird'}, {id:3, name:'Cat'} ]; const filterBird = (data) => data.id !== 2; const filtered1 = data1.filter(filterBird); const filtered2 = data2.filter(filterBird) const output = filtered1.concat(filtered2); alert(JSON.stringify(output)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM