[英]Compare two arrays of different lengths and exclude matches
I have two JSON arrays: 我有两个JSON数组:
{"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
? 如何比较node.js中的两者并仅返回
Array1
的差异?
I have attempted the following: 我尝试了以下操作:
if (Array1.every(function (u, i) { return u._id === Array2[i]._id;})) {
Array1.splice(i, 1);
}
I wouldn't use Array.prototype.every
for the task of filtering out the identical _id
s, as that is not its intended function. 我不会使用
Array.prototype.every
来过滤掉相同的_id
,因为这不是它的预期功能。
Instead, I suggest you use the Array.prototype.filter
method, along with Array.prototype.map
, as shown below: 相反,我建议您使用
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));
ES5: 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; }));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.