Union of Array of Objects in JavaScript?

前端 未结 6 941
予麋鹿
予麋鹿 2020-12-03 12:11

So after searching the interwebz for a few hours I have not found the solution I am looking for.

I have two arrays that contain game objects with a lot of informatio

6条回答
  •  青春惊慌失措
    2020-12-03 12:59

    You can do it using the underscore way:

    // collectionUnion(*arrays, iteratee)
    function collectionUnion() {
        var args = Array.prototype.slice.call(arguments);
        var it = args.pop();
    
        return _.uniq(_.flatten(args, true), it);
    }
    

    It just an improvment of the original function _.union(*arrays), adding an iteratee to work collection (array of object).

    Here how to use it:

    var result = collectionUnion(a, b, c, function (item) {
        return item.id;
    });
    

    The original function which is just working with array, looks like that:

    _.union = function() {
      return _.uniq(flatten(arguments, true, true));
    };
    

    And in bonus a full example:

    // collectionUnion(*arrays, iteratee)
    function collectionUnion() {
        var args = Array.prototype.slice.call(arguments);
        var it = args.pop();
    
        return _.uniq(_.flatten(args, true), it);
    }
    
    var a = [{id: 0}, {id: 1}, {id: 2}];
    var b = [{id: 2}, {id: 3}];
    var c = [{id: 0}, {id: 1}, {id: 2}];
    
    var result = collectionUnion(a, b, c, function (item) {
        return item.id;
    });
    
    console.log(result); // [ { id: 0 }, { id: 1 }, { id: 2 }, { id: 3 } ]
    

提交回复
热议问题