DEV Community

Chris Cook
Chris Cook

Posted on

4 1

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (1)

Collapse
 
niklampe profile image
Nik

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

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay