1

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]

stark0323
  • 71
  • 1
  • 8
  • 1
    They seem to be asking about the intersection of the lists. – Carcigenicate Jul 14 '18 at 18:11
  • 1
    rather than revinvent the wheel, check this out: https://stackoverflow.com/questions/37320296/how-to-calculate-intersection-of-multiple-arrays-in-javascript-and-what-does-e – james emanon Jul 14 '18 at 18:13
  • 1
    What exactly is NJOIN? Do you mean intersection? – jfriend00 Jul 14 '18 at 18:18
  • Woops! Was thinking of SQL – stark0323 Jul 14 '18 at 18:30
  • In the future, if you mean to respond to a specific person's comment, then use put @username in your comment. That's the ONLY way they will get notified that you've done something you want them to see. Otherwise, they'll never see your comment. – jfriend00 Jul 15 '18 at 23:04

2 Answers2

3

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

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)
Mark
  • 90,562
  • 7
  • 108
  • 148