Get the Difference between Two Arrays in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 17, 2021

banner

Photo from Unsplash

Get the Difference between two Arrays #

To get the difference between two arrays:

  1. Use the filter() method to iterate over the first array.
  2. Check if each element is not contained in the second array.
  3. Repeat the steps, but this time iterate over the second array.
index.js
const arr1 = ['a', 'b', 'c', 'd']; const arr2 = ['a', 'b']; function getDifference(a, b) { return a.filter(element => { return !b.includes(element); }); } // 👇️ ['c', 'd'] console.log(getDifference(arr1, arr2));

The function we pass to the Array.filter method gets invoked with each element in the array.

On each iteration we check if the element is NOT contained in the other array.

The filter method returns an array containing the elements that satisfy the condition, in other words the elements from the first array that are not contained in the second array.

However, this doesn't return the complete difference between the arrays, because we only check if the elements from the first array are not contained in the second array. We didn't check if the elements from the second array are not contained in the first array.
index.js
const arr1 = ['a', 'b']; const arr2 = ['a', 'b', 'c', 'd']; function getDifference(a, b) { return a.filter(element => { return !b.includes(element); }); } // 👇️ [] console.log(getDifference(arr1, arr2));

Here's the same code, however we switched the values of the arr1 and arr2 variables. Now arr2 contains 4 elements.

Since we only iterate over arr1, which only has 2 elements that are both contained in arr2, the method returns an empty array.

We would have expected a return value of ['c', 'd'] instead.

To solve this problem, we need to call the getDifference method two times and combine the results.
index.js
const arr1 = ['a', 'b']; const arr2 = ['a', 'b', 'c', 'd']; function getDifference(a, b) { return a.filter(element => { return !b.includes(element); }); } const difference = [ ...getDifference(arr1, arr2), ...getDifference(arr2, arr1) ]; console.log(difference); // 👉️ ['c', 'd']

Here's what we did to get this working:

  1. Call the filter method on the first array and return only the elements that are not contained in the second array.
  2. Call the filter method on the second array and return only the elements that are not contained in the first array.
  3. We combined the results from the two arrays into a third array, using the spread operator (...) syntax.

An easy way to think about the spread operator (...) is that we are unpacking the values of one array into another array.

Now our example is complete and returns the difference between the two arrays.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.