const findIntersectingValues = (arrays) => {
return arrays.reduce((acc, next_array) => {
return acc.filter((value) => {
return next_array.includes(value);
});
});
};
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!
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]
The findIntersectingValues
takes an array of arrays as its only argument then the function works in four simple steps:
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]
[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);
});
});
});
};
findIntersectingValues([
[
{ id: 1, name: "Mac" },
{ id: 2, name: "Gregor" },
],
[{ id: 1, name: "Mac" }],
]);
// [{ id: 1, name: "Mac" }]
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! ðŸ§
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: