Let's 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 values that are found only in one of the arrays. In other words, we will remove the existing ones in both arrays.
We will use 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!
The process:,
- 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 that aren't included in arrayTwo.
- 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 that aren't included in arrayOne.
- 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.
Feel free to share your own solution in the comments! 🔥
Top comments (0)