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

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

    You can create a reusable function to prevent code duplication. Just switch over to the function parameter. Also note that the inner loop is simple for loop so that we can use break and avoid unnecessary checks.

    var firstArray = [];
    var secondArray = [];
    var myFirstObjArray = [{foo: 1, bar: 1}, {foo: 3, bar: 3}, {foo: 4, bar: 5}];
    var mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}];
    
    function difference(myFirstObjArray, mySecondObjArray){
      var firstArray = [];
      myFirstObjArray.forEach((obj)=>{
       var match = false;
       for(var i=0; i

提交回复
热议问题