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

后端 未结 10 1140
春和景丽
春和景丽 2020-12-02 15:49
_.intersection([], [])

only works with primitive types, right?

It doesn\'t work with objects. How can I make it work with objects (maybe b

10条回答
  •  天命终不由人
    2020-12-02 15:57

    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/

提交回复
热议问题