Andreas Dominguez
Andreas Dominguez

Reputation: 65

Compare two arrays and get the elements that are only contained in one

I have two arrays. I want to find the elements with properties that are only contained in the oldDataarr.

I tried this:

for (var k = 0; k < oldDataarr.length; k++) {
  var checker = false;
  for (var l = 0; l < compaar.length; l++) {
    if (oldDataarr[k].name === compaar[l].name && oldDataarr[k].postalCode === compaar[l].postalCode) {
      checker == true;
    }else if (l===compaar.length-1 && checker===false) {
      console.log(oldDataarr[k]);
    }
  }
}

Upvotes: 1

Views: 65

Answers (1)

Scott Schwalbe
Scott Schwalbe

Reputation: 430

I would use the filter and some methods on the array prototype

oldDataarr.filter(function(data) {
  return !compaar.some(function(compData) {
    return data.name === compData.name &&
           data.postalCode === compData.postalCode
  });
});

this will return an array of elements only found in oldDataarr

Upvotes: 1

Related Questions