I've seen previously how to take the intersect between two sets: Javascript: Set Data Structure: intersect
For example,
let a = new Set([1,2,3])
let b = new Set([1,2,4])
let intersect = new Set([...a].filter(i => b.has(i)));
But how do I extend this to a general solution with multiple (very many) sets? E.g. like this:
let a = new Set([1,2,3])
let b = new Set([1,2,4])
let c = new Set([1,2,4,5])
...
let n = new Set([1,2])
let intersect = ...
I would like to define a function that returns the intersection of an unknown amount of sets, if possible
function intersection(a, ...args) {
return ...
}
EDIT/Solution
Thanks to the comments I managed to come up with a solution:
function intersect(setA, setB, ...args) {
const intersection = new Set([...setA].filter((i) => setB.has(i)))
if (args.length === 0) return intersection
return intersect(intersection, args.shift(), ...args)
}