Search code examples
javascriptarraysjavascript-objects

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


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}, {foo: 4, bar: 5}];
mySecondObjArray = [{foo: 2}, {foo: 4}, {foo: 5}];

I need to get two separate arrays containing the values of key foo, the first containing the ones that are in the first array but not in the second, based on the value of key foo, and the second that are in mySecondObjArray but not in myFirstObjArray.

Is there a way to do this without

for(i=0;i<myFirstObjArray.length;i++)
   for(j=0;j<mySecondObjArray .length;j++)
      {...build first array here}

for(i=0;i<mySecondObjArray .length;i++)
   for(j=0;j<myFirstObjArray.length;j++)
      {...build second array here}

? Perhaps my question is a duplicate one that I didn't find, so please be gentle.

Expected output:

firstArray = [{foo: 1}, {foo: 3}];
secondArray = [{foo: 2}, {foo: 5}];

Solution

  • You can simply filter one array's elements by setting the condition based on other array's elements like.

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

    Ps:

    The some() method tests whether at least one element in the array passes the test implemented by the provided function. And I've added a function which just checks if foo property exists in the other array with the same value to be able to filter from the first array.

    At the end you can use .map to filter out the desired key value pairs

    Hope that makes sense

    Read more about .some and filter