_.intersection([], [])
only works with primitive types, right?
It doesn't work with objects. How can I make it work with objects (maybe by checking the "Id" field)?
var a = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ]
var b = [ {'id': 1, 'name': 'jake' }, {'id': 9, 'name': 'nick'} ]
In this example, the result should be:
_.intersection(a, b);
[ {'id': 1, 'name': 'jake' } ];
You can create another function based on underscore's function. You only have to change one line of code from the original function:
In this case you'd now be using underscore's isEqual() method instead of JavaScript's equality comparer. I tried it with your example and it worked. Here is an excerpt from underscore's documentation regarding the isEqual function:
You can find the documentation here: http://documentcloud.github.com/underscore/#isEqual
I put up the code on jsFiddle so you can test and confirm it: http://jsfiddle.net/luisperezphd/jrJxT/
The array methods in underscore are very powerful, you should only need a few lines to accomplish what you want to do:
If you have large arrays you can get rid of the
compact()
call with one additional line:Here is an alternative algorithm that should be flexible and perform better. One of those improvements is that you can specify your own comparison function so in your case you can just compare the id if it's a unique identifier.
You can use it like this:
Or you can leave out the function and it will use underscores _.isEqual() function, like so:
You can find it on jsFiddle here: http://jsfiddle.net/luisperezphd/43vksdn6/
I'd like to share my general solution for those cases.
I added a general function to underscore, using mixin, which performs a binary 'array' operation on two collections, according to a given Hash function:
Usage example:
Note that 'id' may be replaced with a function.
I believe this solution is O(n+m).
Technically, it does work on objects, but you need to be careful of reference equality.