Rudolf Lamprecht Rudolf Lamprecht - 6 months ago 34
Node.js Question

Compare two arrays of different lengths and exclude matches

I have two JSON arrays:

{"Array1":[
{ "_id": "1234"},
{ "_id": "5678"},
{ "_id": "3456"} ]}


and

{"Array2":[
{ "_id": "1234"},
{ "_id": "5678"} ]}


How do I compare the two in node.js and return only the difference from
Array1
?

I have attempted the following:

if (Array1.every(function (u, i) { return u._id === Array2[i]._id;})) {
Array1.splice(i, 1);
}

Answer

I wouldn't use Array.prototype.every for the task of filtering out the identical _ids, as that is not its intended function.

Instead, I suggest you use the Array.prototype.filter method, along with Array.prototype.map, as shown below:

const obj1 = {"Array1":[ 
  { "_id": "1234"},
  { "_id": "5678"}, 
  { "_id": "3456"} ]};

const obj2 = {"Array2":[ 
  { "_id": "1234"},
  { "_id": "5678"} ]};


console.log(obj1.Array1.filter(a1 => obj2.Array2.map(a2 => a2._id).indexOf(a1._id) < 0));

ES5:

var obj1 = {"Array1":[ 
  { "_id": "1234"},
  { "_id": "5678"}, 
  { "_id": "3456"} ]};

var obj2 = {"Array2":[ 
  { "_id": "1234"},
  { "_id": "5678"} ]};


console.log(obj1.Array1.filter(function (a1) { 
  return obj2.Array2.map(function (a2) { 
    return a2._id; 
  }).indexOf(a1._id) < 0;
}));

Comments