_.intersection([], [])
only works with primitive types, right?
It doesn\'t work with objects. How can I make it work with objects (maybe b
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:
_.mixin({
collectionOperation: function(arr1, arr2, hash, action) {
var iArr1 = _(arr1).indexBy(hash)
, iArr2 = _(arr2).indexBy(hash);
return action(_(iArr1).keys(), _(iArr2).keys()).map(function (id) {
return iArr1[id] || iArr2[id];
});
}
});
Usage example:
_([{id:1,v:'q'},{id:2,v:'p'}]).collectionOperation([{id:3,v:'pq'}], 'id', _.union )
Note that 'id' may be replaced with a function.
I believe this solution is O(n+m).