简体   繁体   中英

Javascript array difference

I have two arrays like so

data = [{id: 1, name: apple},
{id: 2, name: mango},
{id: 3, name: grapes},
{id: 4, name: banana}]

data2 =[{id: 1, name: apple},
{id: 3, name grapes}]

My Expected result would be:

[{ id: 2, name: mango}, 
{id:4, name: banana}]

My code is

let finalData =[];
data.forEach(result => {
 data2.find(datum => {
  if(datum['id'] === result['id]{
    finalData.push(result);
   }
 })
})

I am getting wrong result. What is the simplest code or library that I can use?

Your sample data doesn't make sense, but assuming you mean that all data items that have matching IDs also have matching names and also assuming you want a set of all items where the IDs are the same in the two sets of data, you could use a Set to keep track of which IDs are present in one array then filter the second array by those that have their IDs in the set:

const idsInFirst = new Set(data.map(d => d.id));
const intersection = data2.filter(d => idsInFirst.has(d.id));

The reason why an intermediate Set structure is used is because it allows O(1) lookups after a one-time scan, which is more efficient than repeatedly scanning the first array over and over.

If you meant to say you wanted a difference between data sets (items excluded from data that are in data2 ), you'd want to negate/inverse things a bit:

const idsToExclude = new Set(data2.map(d => d.id));
const difference = data.filter(d => !idsToExclude.has(d.id));

Edit

After your clarifying edit, it's that second block of code that you'll want.

I would say a good way to do that is filtering your longest array using a function that will validate if the object id is present in both arrays. Check this example:

 const data = [ {id: 1, name: 'apple'}, {id: 2, name: 'mango'}, {id: 3, name: 'grapes'}, {id: 4, name: 'banana'} ] const data2 =[ {id: 1, name: 'apple' }, {id: 3, name: 'grapes' } ] const longest = data.length > data2.length ? data : data2; const shortest = data.length <= data2.length ? data : data2; const finalData = longest.filter( obj => !shortest.find( o => o.id === obj.id ) ) console.log(finalData)

Good luck!

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