JavaScript 返回一个包含所有子数组中出现的所有字符串的数组

javascriptweb developmentobject oriented programming更新于 2025/10/27 8:44:17

我们有一个像这样的数组数组 −

const arr = [
   ['foo', 'bar', 'hey', 'oi'],
   ['foo', 'bar', 'hey'],
   ['foo', 'bar', 'anything'],
   ['bar', 'anything']
]

我们需要编写一个 JavaScript 函数,该函数接受这样的数组并返回一个包含所有子数组中出现的所有字符串的数组。

让我们为这个函数编写代码

示例

const arr = [
   ['foo', 'bar', 'hey', 'oi'],
   ['foo', 'bar', 'hey'],
   ['foo', 'bar', 'anything'],
   ['bar', 'anything']
]
const commonArray = arr => {
   return arr.reduce((acc, val, index) => {
      return acc.filter(el => val.indexOf(el) !== -1);
   });
};
console.log(commonArray(arr));

输出

控制台中的输出将是 −

['bar']

相关文章


有用资源