0

how to dynamically convert this type of array:

[
    [a,b,c],
    [d,e,f],
]

into

[
    [a,d],
    [b,e],
    [c,f],
]

the length of the first array is not always the same size.

tried the following

for (var i = 0; i < multi.length; i++) { // 2
    for (var j = 0; j < multi[i].length; j++) { // 3
        multi2[j].push(multi[j][i])
    }
}

it does not work

VictorVH
  • 327
  • 1
  • 4
  • 14

1 Answers1

-1

Two issues:

  1. Initialize your multi2 subarray for i.
  2. You have your i and j mixed up in the inner loop.

Here's a fiddle

var multi = [
  ["a","b","c"],
  ["d","e","f"],
  ["g","h","i"],
]
var multi2 = [];

for (var i = 0; i < multi.length; i++) { // 3
  for (var j = 0; j < multi[i].length; j++) { // 3
    multi2[j] = multi2[j]||[]; // initialize subarray if necessary
    multi2[j].push(multi[i][j])
  }
}
cbayram
  • 2,259
  • 11
  • 9