How to Find the Symmetric Difference Between Two Arrays in JavaScript
Source: Dev.to
Approach Overview
We compare two arrays and return a new array that contains only the values that exist in one array but not in both. In other words, we remove the values that appear in both arrays.
Step 1: Filter arrayOne
arrayOne.filter(item => !arrayTwo.includes(item))
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.
Step 2: Filter arrayTwo
arrayTwo.filter(item => !arrayOne.includes(item))
This time we return only the values that are not included in arrayOne.
Step 3: Merge the results
const result = arrayOne
.filter(item => !arrayTwo.includes(item))
.concat(arrayTwo.filter(item => !arrayOne.includes(item)));
We merge the two filtered arrays using Array.prototype.concat(). The final array (result) contains the symmetric difference between the two original arrays—the values that appear in only one of the arrays.
This method is simple, readable, and easy to understand, making it a good choice for beginners. Feel free to share your own solution in the comments! 🔥