Gab
Gab

Reputation: 2276

Using JavaScript to compare 2 arrays and create a new array of objects which does not contains the objects that match by id field

I have two arrays of objects. I would like to use JavaScript to create a new array which does not contains object that match by id field.

First array

[{id: 1, name: "Jo"},{id: 2, name: "Pat"},{id: 3, name: "Mike"}]

Second array

[{id: 1, name: "Jo"},{id: 2, name: "Pat"},{id: 3, name: "Mike"}, {id: 4, name: "Mitch"}, {id: 5, name: "Karl"}]

should return this array

[{id: 4, name: "Mitch"}, {id: 5, name: "Karl"}]

Using lodash would be better if possible. Please note that the first array is always smaller or equal to the second one and can only contain objects that are in the second one.

So I tried the following...

let newArray = _.reject(secondArray, {'id': firstArray});

Without success, I need help with the syntax.

Many thanks for your time and help.

Upvotes: 2

Views: 1989

Answers (1)

Hatchet
Hatchet

Reputation: 5428

Short and sweet. (Assumes one holds the first array and two holds the second array)

var oneIDs = one.map(function (a) {return a.id});

var result = two.filter(function (a) {
    return oneIDs.indexOf(a.id) === -1;
});

Explanation:

First, get a lookup array of all the id's of the elements in the first array.

Second, get all the elements of the second array whose id's are not in the lookup array (oneIDs).

Upvotes: 4

Related Questions