Find symmetric difference between two arrays in JavaScript
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:
- Find the elements of the first array which are not in the second array.
- 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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const first = [ 1, 2, 3, 4, 5 ]; const second = [ 4, 5, 6 ]; const x = first.filter(x => !second.includes(x)); const y = second.filter(x => !first.includes(x)); const difference = x.concat(y); console.log(difference); /* Output: [ 1, 2, 3, 6 ] */ |
With ES7, you can use the includes() method with the Spread syntax:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function diff(first, second) { return [ ...first.filter(x => !second.includes(x)), ...second.filter(x => !first.includes(x)) ]; } const first = [ 1, 2, 3, 4, 5 ]; const second = [ 4, 5, 6 ]; const difference = diff(first, second); console.log(difference); /* Output: [ 1, 2, 3, 6 ] */ |
You can improve the performance by converting both arrays into ES6 Set objects first.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
function diff(first, second) { const a = new Set(first); const b = new Set(second); return [ ...first.filter(x => !b.has(x)), ...second.filter(x => !a.has(x)) ]; } const first = [ 1, 2, 3, 4, 5 ]; const second = [ 4, 5, 6 ]; const difference = diff(first, second); console.log(difference); /* Output: [ 1, 2, 3, 6 ] */ |
2. Using Lodash Library
The Lodash library offers the _.xor method, which returns the symmetric difference of the given arrays.
|
1 2 3 4 5 6 7 8 9 10 11 |
const _ = require('lodash'); const first = [ 1, 2, 3, 4, 5 ]; const second = [ 4, 5, 6 ]; const difference = _.xor(first, second); console.log(difference); /* Output: [ 1, 2, 3, 6 ] */ |
3. Using jQuery
With jQuery, you can use the .not() method to get the symmetric difference.
|
1 2 3 4 5 6 7 8 9 |
const first = [ 1, 2, 3, 4, 5 ]; const second = [ 4, 5, 6 ]; const difference = [...$(first).not(second), ...$(second).not(first)]; console.log(difference); /* Output: [ 1, 2, 3, 6 ] */ |
That’s all about finding the symmetric difference of two arrays in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)