如何将3d数组转换为2d数组

时间:2020-11-11 11:59:55

标签: javascript arrays multidimensional-array

我想将3d数组转换为2d数组

所以我的3d数组看起来像这样

[
  [
    ["creative fee (example)"],
    [1000]
  ],
  [
    ["Item 1...", "Item 2..."],
    [600, 1000]
  ],
  [
    ["Item 3...", "Item 4..."],
    [400, 600]
  ]
]

并想要像这样转换为2d数组(预期结果)

[
  ["creative fee (example)", 1000],
  ["Item 1...", 600],
  ["Item 2...", 1000],
  ["Item 3...", 400],
  ["Item 4...", 600]
]

这是我尝试过的方法,但是它太难了

var carry = [
  [
    ["creative fee (example)"],
    [1000]
  ],
  [
    ["Item 1...", "Item 2..."],
    [600, 1000]
  ],
  [
    ["Item 3...", "Item 4..."],
    [400, 600]
  ]
],
result = []
for (var z = 0; z < carry.length; z++) {
  for (var m = 0; m < carry[z].length; m++) {
    for (var t = 0; t < carry[z][m].length; t++) {
     // console.log(carry[z][m][t])
     result[z+t] = []
     result[z+t][m] = carry[z][m][t]
    }
  }
}
console.log(result)

无论如何都要提前谢谢

4 个答案:

答案 0 :(得分:4)

您可以采用Array#flatMap方法和地图对。

let data = [[["creative fee (example)"], [1000]], [["Item 1...", "Item 2..."], [600, 1000]], [["Item 3...", "Item 4..."], [400, 600]]],
    result = data.flatMap(([l, r]) => l.map((v, i) => [v, r[i]]));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

这应该适合您的情况,您只需要使用spreed运算符(...)即可散布项目并将其推入数组(项目)并将结果推入新数组(在这种情况下使用map)

var array2D = carry.map(el => {
  var items = [];
  el.forEach(e => items.push(...e))
  return items;
});

答案 2 :(得分:1)

如果您需要避免Array.flatMap(它在EMCAScript 2019中引入),那么旧的原始方法将是:

  carry.map(elt => [].concat(...elt))

答案 3 :(得分:0)

通过使用flatMap

const result = data.flatMap(([i, j]) => i.map((a, idx) => [a, j[idx]]))

const data = [
      [
        ["creative fee (example)"],
        [1000]
      ],
      [
        ["Item 1...", "Item 2..."],
        [600, 1000]
      ],
      [
        ["Item 3...", "Item 4..."],
        [400, 600]
      ]
    ];

    const result = data.flatMap(([i, j]) => i.map((a, idx) => [a, j[idx]]))

    console.log(result)