Transposing a 2D-array in JavaScript

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

    Many good answers here! I consolidated them into one answer and updated some of the code for a more modern syntax:

    One-liners inspired by Fawad Ghafoor and Óscar Gómez Alcañiz

    function transpose(matrix) {
      return matrix[0].map((col, i) => matrix.map(row => row[i]));
    }
    
    function transpose(matrix) {
      return matrix[0].map((col, c) => matrix.map((row, r) => matrix[r][c]));
    }
    

    Functional approach style with reduce by Andrew Tatomyr

    function transpose(matrix) {
      return matrix.reduce((prev, next) => next.map((item, i) =>
        (prev[i] || []).concat(next[i])
      ), []);
    }
    

    Lodash/Underscore by marcel

    function tranpose(matrix) {
      return _.zip(...matrix);
    }
    
    // Without spread operator.
    function transpose(matrix) {
      return _.zip.apply(_, [[1,2,3], [1,2,3], [1,2,3]])
    }
    

    Vanilla approach

    function transpose(matrix) {
      const rows = matrix.length, cols = matrix[0].length;
      const grid = [];
      for (let j = 0; j < cols; j++) {
        grid[j] = Array(rows);
      }
      for (let i = 0; i < rows; i++) {
        for (let j = 0; j < cols; j++) {
          grid[j][i] = matrix[i][j];
        }
      }
      return grid;
    }
    

    Vanilla in-place ES6 approach inspired by Emanuel Saringan

    function transpose(matrix) {
      for (var i = 0; i < matrix.length; i++) {
        for (var j = 0; j < i; j++) {
          const temp = matrix[i][j];
          matrix[i][j] = matrix[j][i];
          matrix[j][i] = temp;
        }
      }
    }
    
    // Using destructing
    function transpose(matrix) {
      for (var i = 0; i < matrix.length; i++) {
        for (var j = 0; j < i; j++) {
          [matrix[i][j], matrix[j][i]] = [matrix[j][i], matrix[i][j]];
        }
      }
    }
    

提交回复
热议问题