javascript - 使用另一个数组中的值返回数组数组中的数组
问题描述
我有数组 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)
解决方案
尝试这个
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
推荐阅读
- angular - 无法读取未定义的属性“userService”-实现异步验证器(Angular 12)
- asp.net-mvc - 如何在 ASP.NET 中修复此错误空引用并放置控制器代码?
- javascript - 中间出现缝隙
- javascript - discord ban 命令可供所有用户使用 node.js
- wordpress - 显示子类别的帖子
- javascript - 错误:必须使用 import 加载 ES 模块:不支持 ES 模块的 D:\node_modules\react-markdown\index.js require()
- amazon-web-services - 使用 terraform 模块向路由表添加额外路由
- sql-server - 在事务外使用“with (nolock)
- c++ - 存储可以在交换机中使用而无需显式转换的固定长度的命名常量集合的最佳数据结构是什么?
- websphere-liberty - 如何在 AWS 上缓存与 IBM WebSphere Liberty 的会话?