_.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' } ];
Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.
Adding Underscore to a Node. Once added, underscore can be referred in any of the Node. js modules using the CommonJS syntax: var _ = require('underscore'); Now we can use the object underscore (_) to operate on objects, arrays and functions.
Underscore. JS is a popular javascript based library which provides 100+ functions to facilitate web development. It provides helper functions like map, filter, invoke as well as function binding, javascript templating, deep equality checks, creating indexes and so on.
_. each is synchronous, and will only return after the function was executed on all items. If that. get is asynchronous, each won't help you with that.
You can create another function based on underscore's function. You only have to change one line of code from the original function:
_.intersectionObjects = function(array) { var slice = Array.prototype.slice; // added this line as a utility var rest = slice.call(arguments, 1); return _.filter(_.uniq(array), function(item) { return _.every(rest, function(other) { //return _.indexOf(other, item) >= 0; return _.any(other, function(element) { return _.isEqual(element, item); }); }); }); };
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:
_.isEqual(object, other) Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With