DEV Community

Cover image for How to Find the Symmetric Difference Between Two Arrays in JavaScript
Ekaterine Mitagvaria
Ekaterine Mitagvaria

Posted on • Originally published at Medium

How to Find the Symmetric Difference Between Two Arrays in JavaScript

Let’s find the symmetric difference between two arrays in JavaScript. This is a very useful concept, especially for beginners.

We will compare two arrays and return a new array that contains only the values that exist in one array but not in both.

In simple words, we remove the values that appear in both arrays.

We will work with two arrays:

Two arrays


Using Array.prototype.filter()

The filter() method creates a new array by returning only the elements that pass a specific condition.

The plan

  • First, we compare arrayOne with arrayTwo using the includes() method.
  • Second, we compare arrayTwo with arrayOne using includes() again.
  • Finally, we merge the results using Array.prototype.concat().

Let’s get started

Filter arrays

The process

  1. First, we take arrayOne and use the filter() method.

    For each item in arrayOne, we check if it is not included in arrayTwo.

    Only the values that do not exist in arrayTwo are returned.

  2. Next, we take arrayTwo and use filter() again.

    This time, we return only the values that are not included in arrayOne.

  3. Finally, we take the results from steps one and two:

    • values from arrayOne that do not exist in arrayTwo
    • values from arrayTwo that do not exist in arrayOne

We merge them into a single array using the concat() method.


Final result

The final array contains the symmetric difference between the two arrays.

These are the values that appear in only one of the arrays.

There are many other ways to solve this problem in JavaScript. However, if you are a beginner, this approach is simple, readable, and easy to understand.

Feel free to share your own solution in the comments! 🔥

Top comments (0)