-1

I am trying to write a function which takes in n numbers of arrays as arguments and return an array that contain all elements which exist in each of the passed in argument, array intersection. This is what I have so far. There are nested loops in the function, which isn't efficient. Can someone suggest an improvement. Thank you.

function arrayIntersection(...arrays) {
  
  let obj = arrays.reduce((acc, array) => {
    array.forEach(item => {
      acc[item] ? acc[item]++ : acc[item] = 1;
    })
    return acc;
  }, {});
  
  let numbersOfArgument = arrays.length;
  
  return Object.entries(obj).reduce((acc, entry) => {
    if (entry[1] == numbersOfArgument) {
      acc.push(Number(entry[0]));
    }
    return acc;
  }, []);

}

console.log(arrayIntersection([5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20], [5, 10])); // [5]
kbl
  • 129
  • 5

0 Answers0