首页 > 解决方案 > 使用另一个数组中的值返回数组数组中的数组

问题描述

我有数组 aa = [['a'], ['b'], ['c']] 并且我有一个数组 a = ['a', 'b', 'c'] 我需要为 a 中的每个元素获取 aa 中的项目,即我想列出 a 中的元素及其各自在 aa 中的数组,结果应该类似于 a: ['a'] b: ['b'] c: ['c']我尝试了这段代码,但它确实为 a 中的每个元素返回了第一个元素 i aa

我想知道这里有什么问题

const aa = [
  ['a'],
  ['b'],
  ['c']
]
const a = ['a', 'b', 'c']

let b = []
a.forEach((el) => {
  b.push(
    aa.filter((element) => {
      return element.includes(el)
    })
  )
})
console.log(b)

标签: javascriptarrays

解决方案


尝试这个

const aa = [
  ['a'],
  ['b'],
  ['c']
];
const a = ['a', 'b', 'c'];
let b = {};
a.forEach( // loop "a"
  aEl => b[aEl] = aa.filter(   // filter "aa" 
    aaEl => aaEl.includes(aEl) // on array that includes the item from 'a'
  ).flat() // we need to flatten the resulting array before returning it
);
console.log(JSON.stringify(b)); // using stringify to make it readable


推荐阅读