How to use underscore’s “intersection” on objects?

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/

Leave a Comment