Transposing a 2D-array in JavaScript

后端 未结 23 2870
难免孤独
难免孤独 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:26

    I found the above answers either hard to read or too verbose, so I write one myself. And I think this is most intuitive way to implement transpose in linear algebra, you don't do value exchange, but just insert each element into the right place in the new matrix:

    function transpose(matrix) {
      const rows = matrix.length
      const cols = matrix[0].length
    
      let grid = []
      for (let col = 0; col < cols; col++) {
        grid[col] = []
      }
      for (let row = 0; row < rows; row++) {
        for (let col = 0; col < cols; col++) {
          grid[col][row] = matrix[row][col]
        }
      }
      return grid
    }
    

提交回复
热议问题