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]]) // []
How does it work
The findIntersectingValues
takes an array of arrays as its only argument then the function works in four simple steps:
- The reduce() method is used to iterate over each provided array.
- For each iteration it compares the current array with the result obtained from the previous iteration 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:
- The includes() method that checks if values are present in both arrays.
- 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]
-
[1, 2, 3]
compared with[101, 2, 1, 10]
results in[1, 2]
-
[1, 2]
compared with[2, 1]
still results in[1, 2]
- Returning us the final output:
[1, 2]
š
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 the all object like this:
const findIntersectingValues = (arrays) => {
return arrays.reduce((current_array, next_array) => {
return current_array.filter((currentObj) => {
return next_array.some((nextObj) => {
// Compare objects based on their properties
return JSON.stringify(currentObj) === JSON.stringify(nextObj);
});
});
});
};
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! š§
Top comments (0)