Find the symmetric difference between arrays using javascript

Find the symmetric difference between arrays using javascript

In mathematics, the symmetric difference of two sets, also known as the disjunctive union, is the set of elements which are in either of the sets, but not in their intersection.

The mathematical term symmetric difference (△ or ⊕) of two sets is the set of elements that 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}.

const diff = ( arr1, arr2 ) => [
    ...arr1.filter(e => !arr2.includes(e)),
    ...arr2.filter(e => !arr1.includes(e))
  ];
const symDifference = (...args) => [...new Set(args.reduce(diff))];

console.log(symDifference([1, 2, 3], [5, 2, 1, 4])); 
// [3, 4, 5]
console.log(symDifference([1, 1, 2, 5], [2, 2, 3, 5], [3, 4, 5, 5]));  
// [1, 4, 5]

Leave a Comment

Your email address will not be published. Required fields are marked *