简体   繁体   中英

How to compare two arrays and return a difference in JavaScript

I am building an app using ReactJS library and trying to figure out how to return a difference after comparing two arrays.

const a = [8,10,13,14];
const b = [{id: 8}, {id: 13}, {id: 14}];

and what I would like to get is [10] .

What I have tried and didn't work was using map and filter together.

const newArray = b.map((itemB) => {
    return a.filter(
       itemA => itemB.id !== itemA,
    );
});

What is the simple way of returning this?

Thanks.

Why don't you just filter the unwanted id?

 const a = [8, 10, 13, 14]; const b = [{ id: 8 }, { id: 13 }, { id: 14 }]; console.log(a.filter(num => !b.some(({ id }) => id === num))); 

As you have two array with different item-types, you could combine Array.filter() with Array.map() to get the difference:

 const a = [8,10,13,14]; const b = [{id: 8}, {id: 13}, {id: 14}]; const normalized = b.map(({ id }) => id); const diff = a.filter(value => !normalized.includes(value)); console.log(diff); 

EDIT: I think @Brian Le's solution with .some() is more elegant (and probably more performant)!

您可以使用lodash。

const diff = _.difference(a, b.map(({ id }) => id));

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