Transposing a 2D-array in JavaScript

后端 未结 23 2789
难免孤独
难免孤独 2020-11-22 01:40

I\'ve got an array of arrays, something like:

[
    [1,2,3],
    [1,2,3],
    [1,2,3],
]

I would like to transpose it to get the following

23条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 02:28

    Just another variation using Array.map. Using indexes allows to transpose matrices where M != N:

    // Get just the first row to iterate columns first
    var t = matrix[0].map(function (col, c) {
        // For each column, iterate all rows
        return matrix.map(function (row, r) { 
            return matrix[r][c]; 
        }); 
    });
    

    All there is to transposing is mapping the elements column-first, and then by row.

提交回复
热议问题