如何使用 JavaScript 进行多维数组交集?

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 18:52:17

我们需要编写一个 JavaScript 函数,该函数接受一个多维数组,该数组包含文字值。我们的函数应返回输入数组中存在的所有子数组的交集数组。

示例

其代码为 −

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));

输出

控制台中的输出将是 −

[ 'universal' ]

相关文章


有用资源