This post will discuss how to find the symmetric difference of two arrays in JavaScript. The solution should return all elements in either the first and second array, but not both.

For example, the symmetric difference between arrays [1,2,3,4,5] and [4,5,6] is [1,2,3].

1. Using Array.prototype.filter() function

You can use the filter() method to find the symmetric difference of two arrays. You can do this filtering in two steps:

  1. Find the elements of the first array which are not in the second array.
  2. Find the elements of the second array which are not in the first array.

Then the symmetric difference would be a concatenation of (1) with (2). This method is demonstrated below:

Download  Run Code

 
With ES7, you can use the includes() method with the Spread syntax:

Download  Run Code

 
You can improve the performance by converting both arrays into ES6 Set objects first.

Download  Run Code

2. Using Lodash Library

The Lodash library offers the _.xor method, which returns the symmetric difference of the given arrays.

Download Code

3. Using jQuery

With jQuery, you can use the .not() method to get the symmetric difference.

That’s all about finding the symmetric difference of two arrays in JavaScript.