The mathematical term symmetric difference (â–³
or ⊕
) of two sets is the set of elements which are in either of the two sets but not in both. For example, for sets A = {1, 2, 3}
and B = {2, 3, 4}
, A â–³ B = {1, 4}
.
Symmetric difference is a binary operation, which means it operates on only two elements. So to evaluate an expression involving symmetric differences among three elements (A â–³ B â–³ C
), you must complete one operation at a time. Thus, for sets A
and B
above, and C = {2, 3}
, A â–³ B â–³ C = (A â–³ B) â–³ C = {1, 4} â–³ {2, 3} = {1, 2, 3, 4}
.
Create a function that takes two or more arrays and returns an array of their symmetric difference. The returned array must contain only unique values (no duplicates).
function sym(...args) {
const set1 = new Set(args[0]);
for(let i=1;i<args.length;i++){
const set2 = new Set(args[i]);
set2.forEach(function(element){
if(set1.has(element)){
set1.delete(element)
}else{
set1.add(element);
}
})
}
return [...set1].sort();
}