比较两个不同长度的数组并排除匹配

时间:2016-05-24 08:28:20

标签: javascript node.js

我有两个JSON数组:

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

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

如何比较node.js中的两个并仅返回Array1的差异?

我尝试过以下方法:

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

1 个答案:

答案 0 :(得分:2)

我不会使用Array.prototype.every来过滤相同的_id s,因为这不是它的预期功能。

相反,我建议您使用Array.prototype.filter方法以及Array.prototype.map,如下所示:



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));
&#13;
&#13;
&#13;

<强> ES5:

&#13;
&#13;
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;
}));
&#13;
&#13;
&#13;