Transposing a 2D-array in JavaScript

后端 未结 23 2878
难免孤独
难免孤独 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条回答
  •  -上瘾入骨i
    2020-11-22 02:11

    I didn't find an answer that satisfied me, so I wrote one myself, I think it is easy to understand and implement and suitable for all situations.

        transposeArray: function (mat) {
            let newMat = [];
            for (let j = 0; j < mat[0].length; j++) {  // j are columns
                let temp = [];
                for (let i = 0; i < mat.length; i++) {  // i are rows
                    temp.push(mat[i][j]);  // so temp will be the j(th) column in mat
                }
                newMat.push(temp);  // then just push every column in newMat
            }
            return newMat;
        }
    

提交回复
热议问题