DEV Community

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

Posted on • Edited on

Find the Symmetric Difference Between Two Arrays in JavaScript

The goal of this post is to find the symmetric difference between two arrays in JavaScript which can be very helpful for total beginners.

We will compare two arrays and return a new one with items that are found only in one of the arrays. In other words, we will remove the ones that exist in both arrays.

We will use two arrays:

Two arrays

Using Array.prototype.filter()

The filter() method is a function that creates a new array and returns a value that will pass the specific condition.

The plan will be like this:
a. First, we will compare arrayOne to ArrayTwo using another method includes().
b. Secondly, we will compare ArrayTwo to ArrayOne using includes() once again.
c. Then, we will use a third method Array.prototype.concat() to merge the result of the first two steps.

Let's get started!

Filter arrays

Let's analyze what happened here:

  1. First we took the arrayOne and used a filter() method which returns an array that passes the next condition: check each item in arrayOne and return only those which aren't included in arrayTwo.
  2. Next, we took the arrayTwo and used a filter() method which returns an array that passes the next condition: check each item in arrayTwo and return only those which aren't included in arrayOne.
  3. Finally, we took the results of the first and second steps, the array of items of arrayOne that do not exist in arrayTwo and the array of items of arrayTwo which do not exist in arrayOne, and used concat() method to merge those two.

There are many other ways to do this however if you are a beginner this is all you need to find the symmetric difference between two arrays in JavaScript.

Top comments (0)