Reputation: 2276
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
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