How can I INTERSECT
N arrays in Javascript at a reasonably fast time?
Ie.
arr1 = [1,2,3,4,5];
arr2 = [1,2,3,4];
arr3 = [4];
arr4 = [4,5];
Result: [4]
How can I INTERSECT
N arrays in Javascript at a reasonably fast time?
Ie.
arr1 = [1,2,3,4,5];
arr2 = [1,2,3,4];
arr3 = [4];
arr4 = [4,5];
Result: [4]
You could take an intersection function for common elements with a Set
and Array#filter
.
function common(a, b) {
return b.filter(Set.prototype.has.bind(new Set(a)));
}
console.log([[1, 2, 3, 4, 5], [1, 2, 3, 4], [4], [4, 5]].reduce(common));
I would simply use filter()
and includes()
unless I knew my arrays were going to be very large. This runs "reasonably fast" and is probably faster than creating a bunch of sets when you will be joining a lot of normal-sized arrays, however for fewer, very large arrays, the new Set()
could prove faster :
let arr1 = [1,2,3,4,5];
let arr2 = [1,2,3,4,5];
let arr3 = [4];
let arr4 = [4,5];
let r = [arr1, arr2, arr3, arr4].reduce((a, c) => a.filter(i => c.includes(i)))
console.log(r)