0

I have an Array of Arrays, looking like this:

[
  [val-1-1, val-1-2],
  [val-2-1, val-2-2],
  [val-3-1, val-3-2],
  ...
  [val-n-1, val-n-2]
]

The Array can be really long and what I'd like to achieve is "split" this data structure into two Arrays like so: [val-1-1, val-2-1, val-3-1, ... val-n-1] and [val-1-2, val-2-2, val-3-2, ... val-n-2].

I'm looking for an efficient method to perform this. I know that this is technically easy by looping and using indexes, but I was wondering if there is an efficient method available for this task, as the initial Array is long and I also have multiple of these initial Arrays of Arrays, so looping might take an unnecessarily long time.

Aarni Joensuu
  • 711
  • 8
  • 19

1 Answers1

0

For every column, just check if for that column there's an array in the resultant, if there's already an array then simply push the element, else create a new array and then push.

const transpose = (arr) =>
    arr.reduce(
      (m, r) => (r.forEach((v, i) => ((m[i] ??= []), m[i].push(v))), m),
      []
    ),
  matrix = [
    [1, 2, 3],
    [1, 2, 3],
    [1, 2, 3],
  ];

console.log(transpose(matrix));
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28