You can use the set intersection principle to do this.

By going over each Set in the state using Array#reduce we compare the old Set from the previous iteration with the new Set in the current iteration and only return the intersection of the two.

The first iteration does no comparison as it takes the first set as the starting point:

const state = {
  aSet: new Set().add(1).add(2).add(3).add(4).add(5), // 1,2,3,4,5
  bSet: new Set().add(2).add(3).add(4).add(5).add(6), // 2,3,4,5,6
  cSet: new Set().add(3).add(4).add(5).add(6).add(7), // 3,4,5,6,7
  dSet: new Set().add(4).add(5).add(6).add(7).add(8) // 4,5,6,7,8

const intersection = (sets) => {
  return sets.reduce((prevSet, nextSet, idx) => {
    if (idx === 0) return nextSet;
    return new Set([...nextSet].filter((e) => prevSet.has(e)));
  }, new Set());

const sets = Object.values(state);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top