DEV Community

Discussion on: Common Element in 3 sorted array

Collapse
 
lexlohr profile image
Alex Lohr

Simple JS variant for an arbitrary number of arrays:

const commonItems = (start, ...others) =>
  start.filter(item => others.every(
    array => array.includes(item)
  ))
Enter fullscreen mode Exit fullscreen mode

Optimized version:

const commonItems = (start, ...others) => {
  const maps = others.map(array =>
    new Map(array.map(item => [item, true]))
  )
  return start.filter(item => maps.every(
    array => array.has(item)
  ))
}
Enter fullscreen mode Exit fullscreen mode
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