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:
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
arrayOnewitharrayTwousing theincludes()method. - Second, we compare
arrayTwowitharrayOneusingincludes()again. - Finally, we merge the results using
Array.prototype.concat().
Let’s get started
The process
First, we take arrayOne and use the
filter()method.
For each item inarrayOne, we check if it is not included inarrayTwo.
Only the values that do not exist inarrayTwoare returned.Next, we take arrayTwo and use
filter()again.
This time, we return only the values that are not included inarrayOne.-
Finally, we take the results from steps one and two:
- values from
arrayOnethat do not exist inarrayTwo - values from
arrayTwothat do not exist inarrayOne
- values from
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)