Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use underscore's "intersection" on objects?

_.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' } ];

like image 573
user847495 Avatar asked Dec 29 '11 19:12

user847495


People also ask

Is underscore js still used?

Lodash and Underscore are great modern JavaScript utility libraries, and they are widely used by Front-end developers.

How do you use underscore in JavaScript?

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.

What are underscore 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.

Is underscore each async?

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


1 Answers

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/

like image 194
Luis Perez Avatar answered Oct 02 '22 12:10

Luis Perez