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/