javascript - JavaScript 数组与对象的对称差异

标签 javascript node.js

let arr1 = [{ countryCode: "ITA", index: 2, name: "Italy"}, { countryCode: "NLD", index: 1, name: "Netherlands"}];

let arr2 = [{ countryCode: "NLD", index: 1, name: "Netherlands"}, { countryCode: "BEL", index: 3, name: "Belgium"}];

我希望它返回对称差,所以它应该返回:

[{ countryCode: "ITA", index: 2, name: "Italy"},  {countryCode: "BEL", index: 3, name: "Belgium"}]

如何在 JavaScript 中完成此操作?我尝试执行以下操作:

let difference = arr1
                 .filter(x => !arr2.includes(x))
                 .concat(arr2.filter(x => !arr1.includes(x))); 

但这似乎不适用于其中包含对象的数组。

最佳答案

您可以获取 map 并添加或删除该项目(如果该项目位于 map 中)。

const
    array1 = [{ countryCode: "ITA", index: 2, name: "Italy"}, { countryCode: "NLD", index: 1, name: "Netherlands" }],
    array2 = [{ countryCode: "NLD", index: 1, name: "Netherlands" }, { countryCode: "BEL", index: 3, name: "Belgium" }],
    map = new Map,
    cb = o => map.delete(o.countryCode) || map.set(o.countryCode, o);

array1.forEach(cb);
array2.forEach(cb);

console.log(Array.from(map.values()));

关于javascript - JavaScript 数组与对象的对称差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65835785/

相关文章:

javascript - 如何从 twitter widgets.js 使用 twitter factory

JavaScript/Html Pl/sql 验证器。

Javascript:避免多个弹出框/检查div是否为空

javascript - 在 GAE 上运行 Websocket

node.js - git 推送的更改未反射(reflect)在 heroku 服务器上

javascript闭包局部变量超出范围?

javascript - 单击显示 div 但再次隐藏 + 保持 body 位置

node.js - 确定是否向 Firebase 实时数据库添加或删除数据

node.js - 如何用 Mongoose 只保存日期部分,而不是 ISODate 格式

node.js - 使用 redis-mock 进行 Nodejs 单元测试导致 ECONNREFUSED