DEV Community

Chris Cook
Chris Cook

Posted on

Symmetric Difference of Arrays in JavaScript

The symmetric difference of two arrays are the elements that are present in either one or the other array, but not in both. This means that an element is present in the first array but not in the second, or vice versa.

This is useful when you want to compare two arrays and identify the elements that are unique in each array. On the other hand, using one set alone would only remove duplicates, but would not provide information about the unique elements relative to other sets.

Here's an example to illustrate this difference:

const arrayA = [1, 2, 3, 4];
const arrayB = [3, 4, 5, 6];

const union = new Set([...arrayA, ...arrayB]);
console.log(Array.from(union));
// Output: [1, 2, 3, 4, 5, 6]

const symmetricDifference = (arrayA, arrayB) => {
    // ...
};

const difference = symmetricDifference(arrayA, arrayB);
console.log(difference);
// Output: [1, 2, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Typically, I would use the _.xor() function from Lodash to create the symmetric difference. It even supports more than two arrays and keeps the original order of the elements. However, if we don't need this additional functionality, we can simply implement this function in plain JavaScript:

const symmetricDifference = (arrayA, arrayB) => {
  const setA = new Set(arrayA);
  const setB = new Set(arrayB);

  const diffA = Array.from(setA).filter(x => !setB.has(x));
  const diffB = Array.from(setB).filter(x => !setA.has(x));

  return [...diffA, ...diffB];
};
Enter fullscreen mode Exit fullscreen mode

Interestingly, the plain JavaScript implementation seems to perform much better than Lodash's function on this simple benchmark of two arrays of 100 random elements each. However, I would imagine that the performance of Lodash's function increases with the number of array elements. Therefore, it might not always make sense to implement the function yourself.

Latest comments (1)

Collapse
 
niklampe profile image
Nik

Amazing. Was looking for a solution to my problem, and here it is!