Ever wondered how to find the difference between two arrays without a third party library?
Tags: javascript
Published: 2023-06-29 18:55:56

---
title: Ever wondered how to find the difference between two arrays without a third party library?
published: true
tags: Javascript
canonical_url: https://blog.melvinvmegen.com/snippets/array-difference
---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y4403u9m341u2csdx5wt.png)

## Context

As JavaScript developers, we are constantly working with arrays and as time passed you may have encountered a situation where you needed to compare two arrays and find the difference between them.
In this article, we will explore a code snippet in native javascript that does just that, using only native methods [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce), [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter), [sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) and [includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes). So, let's dive in and learn how to find the difference between two arrays in just one line (just kidding otherwise this oneliner would be prettry much unreadable haha).

## Usage

```js
diffBetweenArrays([
  [1, 2, 3],
  [1, 2],
]); // [3]

diffBetweenArrays([
  [1, 2, 3],
  [1, 2, 3],
]); // []

// ✅ Order doesn't matter
diffBetweenArrays([
  [1, 2, 3, 4, 5],
  [5, 2, 10],
]); // [1, 3, 4]

diffBetweenArrays([
  [5, 2, 10],
  [1, 2, 3, 4, 5],
]); // [1, 3, 4]

// ❌ Avoid more than 2D arrays
diffBetweenArrays([[1, 2, 3], [1, 2], [2]]);
// [3]
```

## How does it work?

The `diffBetweenArrays` takes a 2D array (more would have unexpected result) as its only argument then the function works in a **few simple steps**:

1. First we sort our 2D array by array length with [sort()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) to make sure that the longuest array is always first so that the order at which we provide them doesn't matter.
2. The [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) method is used to iterate over each provided arrays.
3. For each iteration it compares the **next_array** with the result obtained from the previous iteration _(this is why is returns unexpected results when you provide more than 2D array as parameter)_, if none it's initialized as the first array using the [filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) method creating a new array with only the values that satisfy a given condition in our case the condition is provided by:
4. The [includes()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method that checks if any value from the previous iteration is not present in the **next_array**.
5. Lastly the [reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce) method passes the resulting array to the next iteration until all arrays have been compared.

And tada 🎉

```js
diffBetweenArrays([
  ["George", "Saint", "Pierre"],
  ["Saint", "Pierre"],
]);
// ['Conor']
```

**Note:** We could extend this function to match objects aswell with any comparison you'd like, for the sake of the example let's compare all the properties of the object by first converting it to a string like this:

```js
const diffBetweenArrayOfObjects = (arrays) => {
  return arrays
    .sort((current, next) => (current.length > next.length ? -1 : 0))
    .reduce((current_array, next_array) => {
      return current_array.filter((currentObj) => {
        return next_array.some((nextObj) => {
          return JSON.stringify(currentObj) !== JSON.stringify(nextObj);
        });
      });
    });
};

diffBetweenArrayOfObjects([
  [
    { id: 1, name: "George" },
    { id: 2, name: "George Saint-Pierre" },
  ],
  [{ id: 1, name: "George" }],
]);
// [{ id: 2, name: "George Saint-Pierre"" }]
```

## Conclusion

The **diffBetweenArrays** function is a very useful snippet to return the difference between a 2D provided array, as a single array containing only values that are present in the first array but not in the second one.

Keep the good work! 🧠