【问题标题】:How to make new array or arrays with contents from other arrays?如何使用其他数组的内容制作新数组或数组?
【发布时间】:2020-03-11 10:16:53
【问题描述】:

第一个数组:

const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];

第二个数组:

const arr2 = [['some1', 'some2'], ['some3', 'some4']];

想要的数组:

const finalArr = [[1, 2, 3, 4], ['some1', 'some2'], ['some3', 'some4']];

所以,基本上finalArr 应该有arr1 的第一个索引数组和arr2rest

如何做到这一点?

【问题讨论】:

  • const finalArr = [arr1[0], ...arr2] 这应该是诀窍。
  • 我只能为自己说话,对我来说,原因是问题缺乏——什么已经尝试过,什么没用。
  • 你可以阅读this

标签: javascript arrays node.js json sorting


【解决方案1】:

如果您不关心销毁arr2,也不关心拥有arr1[0] 的深层副本,那么简单的unshift() 就可以做到:

const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];
const arr2 = [['some1', 'some2'], ['some3', 'some4']];

arr2.unshift(arr1[0]);
console.log(JSON.stringify(arr2));

当然,这些确实是一些可能不适合您的情况。

【讨论】:

    【解决方案2】:

    使用 ES6 扩展运算符如下。

    const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];
    
    const arr2 = [['some1', 'some2'], ['some3', 'some4']];
    
    const finalArr = [arr1[0], ...arr2];
    
    console.log(finalArr);
    

    或者使用 concat 函数。

    const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];
    const arr2 = [['some1', 'some2'], ['some3', 'some4']];
    const finalArr = [arr1[0]].concat(arr2);
    
    console.log(finalArr);
    

    【讨论】:

      【解决方案3】:
      const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];
      
      const arr2 = [['some1', 'some2'], ['some3', 'some4']];
      cont finalArr = Array();
      finalArr.push(arr1[0]);
      finalArr.push(arr2[0]);
      finalArr.push(arr2[1]);
      

      您还可以遍历数组并动态推送它们。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-19
        • 2019-03-04
        • 2017-07-09
        • 1970-01-01
        相关资源
        最近更新 更多