Taking common elements from many arrays in 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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

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

The output in the console will be −

[2, 1, 3]

Updated on: 22-Oct-2020

423 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements