0

Underscore provides handy function for array intersection, difference and union. But they don't work as expected for array of objects:

var first = {val: 1};
var otherFirst = {val: 1};
var second = {val: 2};
_.difference([first, second], [otherFirst]); // result is [first, second] instead of [second]

This happens because JS checks objects for reference equality. How can I intersect two arrays of objects?

I'm looking for some kind of idiomatic solution.

2 Answers 2

2

I've got something which will work for two arrays.

_.filter([first,second], function(obj){
    return !_.findWhere([otherFirst], obj); 
});

Basically what it's dong it's checking if an object in the array1 is not present in array2 filter that.

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

Comments

0

Using remove will work:

_.remove([first, second], otherFirst)

2 Comments

Does it work when there are more than one element in second array?
No, that would need an explicit callback. And I just noticed that underscore actually doesn't even have a remove method, it is lodash-specific.

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.