Finding intersection of multiple arrays - JavaScript


We are required to write a JavaScript function that takes in any arbitrary number of arrays and returns an array of elements that are common to all arrays. If there are no common elements, then we should return an empty array.

Let’s say the following are our arrays −

const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];

Example

Following is the code −

const arr1 = [2, 6, 7, 1, 7, 8, 4, 3];
const arr2 = [5, ,7, 2, 2, 1, 3];
const arr3 = [1, 56, 345, 6, 54, 2, 68, 85, 3];
const intersection = (arr1, arr2) => {
   const res = [];
   for(let i = 0; i < arr1.length; i++){
      if(!arr2.includes(arr1[i])){
         continue;
      };
      res.push(arr1[i]);
   };
   return res;
};
const intersectMany = (...arrs) => {
   let res = arrs[0].slice();
   for(let i = 1; i < arrs.length; i++){
      res = intersection(res, arrs[i]);
   };
   return res;
};
console.log(intersectMany(arr1, arr2, arr3));

Output

This will produce the following output in console −

[2, 1, 3]

Updated on: 30-Sep-2020

938 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements