【问题标题】:Merge multiple two-dimensional arrays into one two-dimesional array in javascript在javascript中将多个二维数组合并为一个二维数组
【发布时间】:2021-10-21 19:47:14
【问题描述】:

如何将这些数组合并为一个合并数组? 数据来自具有行和列的表。

一个数组包含一整列的数据。

我想将这些列合并为一个包含 3 列的数组。

//array from col 1
let firstArray = [
    [100],      //row 1, col 1
    [200],      //row 2, col 1
    [300]       //row 3, col 1
]

//array from col 2
let secondArray = let firstArray = [
    ['a'],      //row 1, col 2
    ['b'],      //row 2, col 2
    ['c']       //row 3, col 2
]

//array from col 2
let secondArray = let firstArray = [
    ['run'],        //row 1, col 3
    ['hide'],       //row 2, col 3
    ['seek']        //row 3, col 3
]

预期的合并数组输出:

let mergedArray = [
    [100, 'a', 'run'],      //row 1, col 123
    [200, 'b', 'hide'],     //row 2, col 123
    [300, 'b', 'seek']      //row 3, col 123
]

【问题讨论】:

  • 只是在阅读您的问题后才想到,您正在将数组组合成组合数组,因为它们是数据。您可能不是在寻找创建数据模型吗?就像在具有命名属性的对象集合而不是数组集合中一样?通过将返回行更改为例如 return {id:item1[0], char:item2[0],descr: item3[0]}; 来修改接受的答案很容易
  • 上面的数据范围来自谷歌表格,这就是它看起来像这样的原因。

标签: javascript arrays multidimensional-array ecmascript-6 array-merge


【解决方案1】:

const firstArray = [
    [100],      //row 1, col 1
    [200],      //row 2, col 1
    [300]       //row 3, col 1
];
const secondArray = [
    ['a'],      //row 1, col 2
    ['b'],      //row 2, col 2
    ['c']       //row 3, col 2
];
const thirdArray = [
    ['run'],        //row 1, col 3
    ['hide'],       //row 2, col 3
    ['seek']        //row 3, col 3
];

const mergedArray = firstArray.map((item1, i) => {
  const item2 = secondArray[i];
  const item3 = thirdArray[i];
  return [item1[0], item2[0], item3[0]];
});
console.log(mergedArray);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 2017-10-12
    • 2020-11-12
    • 2018-02-09
    • 1970-01-01
    • 2017-12-13
    相关资源
    最近更新 更多