首页 > 解决方案 > 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()或其他东西......有人可以指出我正确的方向吗?

太感谢了!

标签: javascriptnode.jsarraysecmascript-6

解决方案


是的,.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


推荐阅读