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

前端 未结 5 1889
南笙
南笙 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:33

    Here is a small solution with just filter and a map with the foo attribute.

    const myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}];
    const mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}];
    
    const exclude = (arr1, arr2) => arr1.filter(o1 => arr2.map(o2 => o2.foo).indexOf(o1.foo) === -1);
    
    console.log(exclude(myFirstObjArray, mySecondObjArray));
    console.log(exclude(mySecondObjArray, myFirstObjArray));

提交回复
热议问题