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

后端 未结 10 1154
春和景丽
春和景丽 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 16:11

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

提交回复
热议问题