2

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.

3
  • @NickZuber updated the question Commented Mar 4, 2016 at 2:51
  • Much better :) what didn't work about your attempt? I know of a dirty way to solve this problem that uses native JS, but I'm not sure if it'd be what you're looking for Commented Mar 4, 2016 at 3:00
  • 1
    Yes I know, sorry about that. Please look at Hatchet's answer, short and sweet. Commented Mar 4, 2016 at 3:03

1 Answer 1

4

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.