Multiple arrays intersection

Benchmark created on


Setup

const multipleArrays = [
  ["a", "b", "c", "d", "e", "f"],
  ["f", "e", "d", "c", "b", "a"],
  ["a", "b", "c", "d", "e"],
  ["b", "c", "d", "e", "f"],
  ["b", "c", "a", "d"],
  ["c", "e", "d", "f"]
];


function getIntersectionOfMultipleArrays (arrays) {
  return arrays.reduce((previousValue, currentValue) =>
    previousValue.filter((element) => currentValue.includes(element))
  );
}


function getIntersectionOfMultipleArrays2 (arrays) {
  if (arrays.length === 0) return [];
  let intersection = arrays[0].slice(); // Start with a copy of the first array

  for (let i = 1; i < arrays.length; i++) {
    const currentArray = arrays[i];
    let tempIntersection = [];

    for (let j = 0; j < intersection.length; j++) {
      const element = intersection[j];
      for (let k = 0; k < currentArray.length; k++) {
        if (element === currentArray[k]) {
          tempIntersection.push(element);
          break; // Stop searching through currentArray, move to the next element in intersection
        }
      }
    }

    intersection = tempIntersection;
  }

  return intersection;
}

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
getIntersectionOfMultipleArrays(multipleArrays)
ready
for loop
getIntersectionOfMultipleArrays2(multipleArrays)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.