JavaScript get elements from an object array that are not in another

前端 未结 5 1894
南笙
南笙 2020-12-15 18:20

I\'m new in JavaScript programming and I have two object arrays that have the following structure:

myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {fo         


        
5条回答
  •  生来不讨喜
    2020-12-15 18:42

    ES5 without using fat arrow,

    var myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}],
        mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}],
        
        firstArray  = myFirstObjArray.filter(function(o) { return !mySecondObjArray.some(function(i) { return i.foo === o.foo})});
         
        secondArray  = mySecondObjArray.filter(function(o) { return !myFirstObjArray.some(function(i) { return i.foo === o.foo})});
        
        console.log(firstArray)
        console.log(secondArray)

提交回复
热议问题