Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
210 views
in Technique[技术] by (71.8m points)

node.js - symmetric difference for arrays with objects JavaScript

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"}];

I want it to return the symmetric difference, so it should return:

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

How can I accomplish this in Javascript? I tried to do the following:

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

But this doesn't seem to work for arrays with objects in them.

question from:https://stackoverflow.com/questions/65835785/symmetric-difference-for-arrays-with-objects-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could take a Map and add or delete the item, if it is in the 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()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...