Multiple arrays intersection (v4)

Revision 4 of this 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;
}

function getIntersectionOfMultipleArrays3 (arrays) {
  return arrays.reduce((previousValue, currentValue) =>
    previousValue.filter((element) => currentValue.indexOf(element) > -1)
  );
}

function getIntersectionOfMultipleArrays4 (arrays) {
  return arrays.reduce((previousValue, currentValue) =>
    previousValue.filter((element) => currentValue.some(e => e === element))
  );
}

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
getIntersectionOfMultipleArrays(multipleArrays)
ready
for loop
getIntersectionOfMultipleArrays2(multipleArrays)
ready
indexOf
getIntersectionOfMultipleArrays3(multipleArrays)
ready
some
getIntersectionOfMultipleArrays4(multipleArrays)
ready

Revisions

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