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

  • A+
Category:Languages

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 fist containing the ones that are in the first array, 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}]; 

 


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)     console.log(secondArray)

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.

Hope that makes sense

Read more about .some and filter

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: