2

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]

5
  • 1
    They seem to be asking about the intersection of the lists. Commented Jul 14, 2018 at 18:11
  • 1
    rather than revinvent the wheel, check this out: stackoverflow.com/questions/37320296/… Commented Jul 14, 2018 at 18:13
  • 1
    What exactly is NJOIN? Do you mean intersection? Commented Jul 14, 2018 at 18:18
  • Woops! Was thinking of SQL Commented Jul 14, 2018 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. Commented Jul 15, 2018 at 23:04

2 Answers 2

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));

Sign up to request clarification or add additional context in comments.

5 Comments

Is this "reasonably fast" as the OP asked? It creates a new Set() a lot.
for the given data, it is fast to write ... o_O
Nina, can you explain this bit: Set.prototype.has.bind(new Set(a))
@jamesemanon, what i want, is to take a function as callback. in this case has from Set, but it is not possible to use new Set([...]).has, because it returns an error Set.prototype.has: 'this' is not a Set object. therefore i took the prototype and with bind it takes a set as this. voila
imho, that is pretty clever
3

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.