Array Intersection

Have you ever dreamed of finding the intersecting values between arrays without a third party library?


const findIntersectingValues = (arrays) => {
  return arrays.reduce((acc, next_array) => {
    return acc.filter((value) => {
      return next_array.includes(value);
    });
  });
};
js

Context

As a JavaScript developer, we are constantly working with arrays and sometimes we have to find the intersection of multiple arrays. In this article, we will explore the best way to return an array with all the intersecting values between all the provided arrays without the need to use of popular libraries like Lodash or Underscore just relying on the reduce() method in combination with the filter() and the includes, only the best of javascript at work!

Usage

findIntersectingValues([[1, 2, 3], [1]]);
// [1]
findIntersectingValues([
  [1, 2, 3],
  [1, 2, 3],
]);
// [1, 2, 3]
findIntersectingValues([[1, 2, 3], [1], [2]]);
// []
findIntersectingValues([[1, 2, 3], [2], [2]]);
// [2]
js

How does it work

The findIntersectingValues takes an array of arrays as its only argument then the function works in four simple steps:

  1. The reduce() method is used to iterate over each provided arrays.
  2. For each iteration it compares the next_array with the result obtained from the previous iteration, 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:
  3. The includes() method that checks if each values are present in both arrays.
  4. Lastly the reduce() method passes the resulting array to the next iteration until all arrays have been compared.

To provide a more concrete example here is the output of each iteration in this case:

const arrays = [
  [1, 2, 3],
  [101, 2, 1, 10],
  [2, 1],
];

findIntersectionArray(arrays);
// Final Output: [1, 2]
js
  1. [1, 2, 3] compared with [101, 2, 1, 10] results in [1, 2]
  2. [1, 2] compared with [2, 1] still results in [1, 2]
  3. Returning us the final output: [1, 2] 🎉

Conclusion

Finding the intersection of arrays is a common problem in programming, and there are several ways to solve it. In this article, we explored one of the best ways to return an array that is the intersection of all the provided arrays. Whether you choose to use a third-party library or native JavaScript functions, the key is to write code that is concise, readable, and easy to maintain.

Keep the good work! 🧠

Last updated: January 14, 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: