Search code examples
javascriptarraysmatrix

Transpose irregular matrix in JavaScript


I got this matrix that, depending on the results I receive from the server, the width can change. Basically, it can be something like

[undefined, undefined]
[1, 2, 3, 4]
[1, 2]
[undefined, undefined, undefined]
[1, 2, 3, 4, 5, 6]

and I want it to be like this

[undefined, 1, 1, undefined, 1]
[undefined, 2, 2, undefined, 2]
[undefined, 3,undefined, undefined, 3]
[undefined, 4, undefined, undefined, 4]
[undefined, undefined, undefined, undefined, 5]
[undefined, undefined, undefined, undefined, 6]

Notice that the height changed to the maximum width of the first example. I googled it and the best solution I got was this

array.map((row, i) => array.map(col => col[i]))

but this solution wont change my matrix height. I tried 2 for cycles but I think I didn't code it right as I was not getting the expected result. If someone could give me a little help, that would be awesome


Solution

  • There are a lot of ways to solve this (as other answers demonstrate). Here's how I'd do it, as it minimizes the number of times we iterate over the data.

    const data = [
      [undefined, undefined],
      [1, 2, 3, 4],
      [1, 2],
      [undefined, undefined, undefined],
      [1, 2, 3, 4, 5, 6],
    ];
    
    // get the length of the longest array
    const maxLen = data.reduce((max, {length}) => Math.max(max, length), 0);
    
    // make a new set of arrays
    const result = Array.from({ length: maxLen }, (_, i) => data.map(col => col[i]));
    
    console.log(result);