How to get the difference between two arrays in JavaScript

Get asymmetric difference between two arrays

To get the difference between two arrays in JavaScript, use the filter() and include() array methods, like this:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } const arr1 = [1, 2, 3, 4]; const arr2 = [2, 4]; console.log(getDifference(arr1, arr2)); // [1, 3]

Array filter() runs a callback on every element of an array and returns an array of elements that the callback returns true for:

JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter( (number) => number % 2 === 0 ); console.log(evenNumbers); // [2, 4, 6, 8, 10]

The Array includes() method returns true if the Array contains a particular element and returns false if it doesn’t:

JavaScript
const arr = ['a', 'b', 'c']; console.log(arr.includes('b')); // true

If we wanted to find the difference between two Sets, we’d have used Set has() in place of Array includes():

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([2, 4]); console.log(getDifference(set1, set2)); // {1, 3}

Get symmetric difference between two arrays

The method above only gives the methods in the second array that aren’t in the first:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } const arr1 = [1, 3]; const arr2 = [1, 3, 5, 7]; console.log(getDifference(arr1, arr2)); // []

You want this sometimes, especially if arr2 is meant to be arr1‘s subset.

But other times you may want to find the symmetric difference between the arrays; regardless of which one comes first.

To do that, we simply merge the results of two getDifference() calls, each with the order of the arrays reversed:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } function getSymmetricDifference(arrA, arrB) { return [ ...getDifference(arrA, arrB), ...getDifference(arrB, arrA), ]; } const arr1 = [1, 3]; const arr2 = [1, 3, 5, 7]; console.log(getSymmetricDifference(arr1, arr2)); // [5, 7] console.log(getSymmetricDifference(arr2, arr1)); // [5, 7]


Every Crazy Thing JavaScript Does

A captivating guide to the subtle caveats and lesser-known parts of JavaScript.

Every Crazy Thing JavaScript Does

Sign up and receive a free copy immediately.

Leave a Comment

Your email address will not be published. Required fields are marked *