简体   繁体   English

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

[英]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.

相关问题 交替合并两个不同长度的数组,JavaScript - Merge Two arrays of different lengths alternatively, JavaScript 循环遍历两个长度不同的数组 - Looping through two arrays having different lengths 如何映射两个不同长度的数组? (JavaScript)的 - How to map two arrays with different lengths? (Javascript) JavaScript:比较两个数组并返回匹配项的索引 - JavaScript: Compare two arrays and return index of matches JavaScript:比较两个数组并打印匹配项数 - JavaScript: compare two arrays and print the number of matches Javascript程序为两个不同长度的数组找到长度为2的组合 - Javascript program to find combination of length 2 for two arrays of different lengths 比较两个不同长度的数组,并返回包含不常见元素的数组 - comparing two arrays of different lengths and returning an array with the uncommon elements 如何在 Z686155AF75A60A0F36E9D80C1FEZED 中具有不同长度的两个 object arrays 的 map 属性 - how to map properties of two object arrays with different lengths in JavaScript 如何比较两个数组中的值以找到一个或多个匹配项? [jQuery] - How to compare values in two arrays to find one or more matches in? [jQuery] 比较反应中的两个数组并根据名称属性的匹配过滤一个数组 - Compare two arrays in react and filter one based on matches of name property
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM