How to do multidimensional array intersection using JavaScript?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ]
raja
Published on 23-Nov-2020 10:13:33
Advertisements