Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the intersection of n arrays

Using ES6's Set, given two arrays we can get the intersection like so:

let a = new Set([1,2,3])
let b = new Set([1,2,4])
let intersect = new Set([...a].filter(i => b.has(i)));

How can we get the intersection of n arrays?

Update:

I'm trying to wrap my head around this for the following use case. I have a two dimensional array with at least one element.

parts.forEach(part => {
  intersection = new Set()
})

How would you get the intersection of each element (array) in parts?

like image 832
Raphael Rafatpanah Avatar asked Dec 03 '22 13:12

Raphael Rafatpanah


1 Answers

Assuming you have some function function intersect(set1, set2) {...} that can intersect two sets, you can get the intersection of an array of sets using reduce:

function intersect(a, b) {
    return new Set(a.filter(i => b.has(i)));
}

var sets = [new Set([1,2,3]), ...];
var intersection = sets.reduce(intersect);
like image 50
Asad Saeeduddin Avatar answered Dec 20 '22 00:12

Asad Saeeduddin