DEV Community

Discussion on: Common Element in 3 sorted array

Collapse
 
peerreynders profile image
peerreynders • Edited

Just for fun:

const list = [
  [1, 5, 10, 20, 40, 80],
  [6, 7, 20, 80, 100],
  [3, 4, 15, 20, 30, 70, 80, 120],
];
console.log(intersectList(list)); // [20, 80]

function intersect(last, values) {
  const collectCommon = (common, value) =>
    last.has(value) ? common.add(value) : common;
  return values.reduce(collectCommon, new Set());
}

function intersectList(list) {
  const [head, ...tail] = list;
  if (tail.length === 0) return typeof head === 'undefined' ? [] : head;

  return [...tail.reduce(intersect, new Set(head))];
}
Enter fullscreen mode Exit fullscreen mode

For the more imperatively minded:

function intersectList(list) {
  const [head, ...tail] = list;
  if (tail.length === 0) return typeof head === 'undefined' ? [] : head;

  let last = new Set(head);
  for (const xs of tail) {
    const common = new Set();
    for (const x of xs) if (last.has(x)) common.add(x);
    last = common;
  }
  return [...last];
}
Enter fullscreen mode Exit fullscreen mode