【问题标题】:JS Javascript - How to put array values in another array by indexes?JS Javascript - 如何通过索引将数组值放入另一个数组中?
【发布时间】:2021-10-13 02:00:31
【问题描述】:

我有这个数组/对象:

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() 或其他什么...有人能指出我正确的方向吗??

非常感谢!

【问题讨论】:

    标签: javascript node.js arrays ecmascript-6


    【解决方案1】:

    Object.values 会将您的template 转换为数组数组,然后简单地对其进行映射,并在索引上进行另一个内部映射并替换 他们带有来自myArray的特定信件。

    代码:

    const template = {0: [0, 1, 2, 3, 4, 5], 1: [0, 1, 2, 3, 4, 6]}
    
    const myArray = ["Q","W","A","S","Z","X","E","R","D"]
    
    const res = Object.values(template)
                      .map(a => a.map(idx => myArray[idx] ?? null))
    
    console.log(res)
    .as-console-wrapper { max-height: 100% !important; top: 0; } /* ignore this */

    【讨论】:

      【解决方案2】:

      我认为这应该可行:

      const res = templateArr.map( (arr) => {
          
          return arr.map( (index) => {
              return myArray[index]
          })
      })
      

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 如果你有对象,那么可以用templateArr.map 代替Object.values(template).mapObject.keys(template).map(k=> template[k].map())
        猜你喜欢
        • 2015-02-11
        • 1970-01-01
        • 2013-11-13
        • 1970-01-01
        • 2012-10-19
        • 1970-01-01
        • 2021-11-10
        • 1970-01-01
        • 2016-10-08
        相关资源
        最近更新 更多