How to find elements in array2 that are not in array1?

后端 未结 2 1483
無奈伤痛
無奈伤痛 2021-01-28 02:10

I have two arrays:

var a1 = [ { ID: 2, N:0 }, { ID: 1, N:0 } ];
var a2 = [ { ID: 1, N:0 }, { ID: 2, N:0 }, { ID: 3, N:0 } ];

I need to get all

2条回答
  •  猫巷女王i
    2021-01-28 02:54

    The same question has been posted a few times, have a look here:

    JavaScript array difference

    Most solutions are given through 'native' javascript however. I sometimes prefer to use underscore.js, since I build a lot of things using backbone.js and underscore is a dependency for Backbone. So I can use its awesome utilities. You might consider loading them in:

    http://documentcloud.github.com/underscore/

    var a1 = [ { ID: 2, N:0 }, { ID: 1, N:0 } ];
    var a2 = [ { ID: 1, N:0 }, { ID: 2, N:0 }, { ID: 3, N:0 } ];
    
    var from, to;
    if(a1 > a2){
        from = a1
        to = a2
    } else {
        from = a2
        to = a1
    }
    
    var a3 = _.filter(from, function(obj){
        var compare = _.find(to, function(obj2){ return obj.ID === obj2.ID });
        return compare === undefined
    });
    console.log(a3);
    

    I first determined the longest array, I do this because I want to compare as many objects as possible to the shorter list. Otherwise we'd 'forget' some.

    Then I simply use filter and find in the underscore.js library to return the objects that aren't in the shorter array, but ARE in the longer array.

    If both arrays are of equal length it is fine too, because then we'd compare all of the items to all of the others.

提交回复
热议问题