How to do multidimensional array intersection using JavaScript?


We are required to write a JavaScript function that takes in a multidimensional array of arrays of literal values. Our function should return the intersecting array of all the subarrays present in the input array.

Example

The code for this will be −

const arr = [
   ["garden","canons","philips","universal"],
   ["universal","ola","uber","bangalore"]
];
const findMultiIntersection = (arr = []) => {
   const res = [];
   arr.forEach(el => {
      const thisObj = this;
      el.forEach(element => {
         if(!thisObj[element]){
            thisObj[element] = true;
         }
         else{
            res.push(element)
         };
      });
   }, {});
   return res;
};
console.log(findMultiIntersection(arr));

Output

And the output in the console will be −

[ 'universal' ]

Updated on: 23-Nov-2020

286 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements