javascript - JS Javascript - 如何通过索引将数组值放入另一个数组中?
问题描述
我有这个数组/对象:
const template = {0: [0, 1, 2, 3, 4, 5], 1: [0, 1, 2, 3, 4, 6]}
// I have the above but happy to convert the below if it helps:
//const templateArr = [[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 6]]
然后我有一个要映射到该序列中的数组:
const myArray = ["Q","W","A","S","Z","X,"E","R","D"] // for example
我打算它有以下结果:
let myResult = [["Q", "W", "A", "S", "Z", "X"],["Q", "W", "A", "S", "Z", "E"]]
所以 的所有值myArray
都在 设置的位置template
。
我不确定我是否应该使用.map()
或其他东西......有人可以指出我正确的方向吗?
太感谢了!
解决方案
是的,.map()
这里是正确的工具。您可以使用两个,一个外部的从 映射到您的内部数组templateArr
,然后使用内部映射来映射内部数组中的数字(索引),这会将每个数字转换(即:映射)到对应的值索引来自myArray
:
const templateArr = [[0, 1, 2, 3, 4, 5],[0, 1, 2, 3, 4, 6]];
const myArray = ["Q","W","A","S","Z","X","E","R","D"];
const res = templateArr.map(inner => inner.map(idx => myArray[idx]));
console.log(JSON.stringify(res)); // JSON.stringify to pretty-print
推荐阅读
- javascript - 带有 jQuery 代码链接的引导按钮在多次单击后不更新按钮文本
- python - 即使没有 maxDF 参数,如何将 maxDF 设置为 pyspark.ml.feature.CountVectorizer?
- python - 关于写出梯形积分法的问题
- java - Spring 数据事务控制
- c++ - 如何在 gcc 8 上使用 std::filesystem?
- javascript - 如何在更新剩余对象的值时从对象中删除键值对?
- testing - 如何使用 jest 测试 redux saga?
- r - r - 从列表中打印图返回 quosure 错误
- c# - 优化 if -else 语句
- apache - 如何查看谁登录了 apache http 代理服务器