Array difference

Have you ever wondered how to find the difference between two arrays without a third party library?


const diffBetweenArrays = (arrays) => {
  return arrays
    .sort((current, next) => (current.length > next.length ? -1 : 0))
    .reduce((acc, next_array) => {
      return acc.filter((value) => {
        return !next_array.includes(value);
      });
    });
};
js

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(), filter(), sort() and 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

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]
js

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() 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() 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() 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() method that checks if any value from the previous iteration is not present in the next_array.
  5. Lastly the reduce() method passes the resulting array to the next iteration until all arrays have been compared.

And tada 🎉

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

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! 🧠

Last updated: January 21, 2023

⚡ Who am i to talk about this? ⚡

Honestly i am no one, i've just been coding for 3 years now and i like to document every solutions to every problem i encounter. Extracting as much code snippets and tutorials i can so that if i ever need it again i just have to pop back here and get a quick refresher.

Feel free to me through this learning journey by providing any feedback and if you wanna support me: