Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert 3d array to 2d array

I want to convert 3d array to 2d array

so I have 3d array look like this

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

and want to convert to 2d array like this (expected result)

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

this is what I've tried but it begins too hard

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)

Anyways thank you in advance

like image 398
zummon Avatar asked May 10 '26 00:05

zummon


1 Answers

You could take a Array#flatMap approach and map pairs.

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; }
like image 132
Nina Scholz Avatar answered May 11 '26 13:05

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!