Symmetric Difference:
The symmetric difference between sets A and B is the set that contains the
elements that are present in both sets except the common elements.The symmetric
difference between two sets A and B is represented by A Δ B or A ? B.
e.g.
Set A = {1, 2, 3, 4, 5}
Set B = {3, 5}
So, the symmetric difference between the given sets A and B is {1, 2, 4}
Or, we can say that A Δ B = {1, 2, 4}.
How to find symmetric difference between sets in javascript?
Code:
function symmetricDifference(a, b) {
let c = [...a, ...b];
//keep unique elements only
let set = new Set(c);
c = Array.from(set);
let d = [];
a.forEach((m) => {
if (b.includes(m)) {
d.push(m);
}
});
let e = c.filter((m) => {
return !d.includes(m);
});
return e;
}
let diff = symmetricDifference([1, 2, 3, 4, 5], [3, 5]);
console.log(diff)
Output:
[ 1, 2, 4 ]
No comments:
Post a Comment