Select Page

Easy Solution to find the Symmetric Difference:

function sym(args) {

 const elements = Array.from(arguments)

 return [... new Set(elements)]; 

sym([1, 2, 3], [5, 2, 1, 4]);

// result [3,5,4]
// if sorted, result [3,4,5]


  • Array.from(arguments) will take all the arguments, so we do not need to set separate arguments in the main function like args1, args2
  • With reduce() method, firstly we will collect all the elements of all the arguments in a single array with concat() method
  • Then we will filter all the elements thoes are not included in a and then not included in b. Index -1 finds not included/ not in the collection.
  • Well, the main job is done. But, this may contain same/duplicate elements as we use concat() method
  • So, now, we will clear the duplicate values from the result with new Set() method, but new Set will result like this Set {3,5,4}. It’s done. But, we need to convert this set to an array to use in our project
  • And, we can do it by Array.from() method or [...setNameHere] sprade operator method
  • Together, it will be like this
Array.from(new Set(elemets));

[ Set(elements)];
// result [3,5,4]
  • And if you want to sort the elements, at the end, use the sort() method like this
 return [ Set(elements)].sort();
 // result [3,4,5]

What is Symmetric Difference?

Symmetric difference (△) of two sets is the set of elements which are in either of the two sets but not in both.

For example, for set A = {1, 2, 3, 4} and set B = {2, 3, 4, 5}, A △ B = {1, 5}.

If you find this solution helpful, please feel free to share it.