Transposing a 2D-array in JavaScript

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

    One-liner that does not change given array.

    a[0].map((col, i) => a.map(([...row]) => row[i]))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:31

    const transpose = array => array[0].map((r, i) => array.map(c => c[i]));
    console.log(transpose([[2, 3, 4], [5, 6, 7]]));

    0 讨论(0)
  • 2020-11-22 02:36
    array[0].map((_, colIndex) => array.map(row => row[colIndex]));
    

    map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

    callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed. [source]

    0 讨论(0)
  • 2020-11-22 02:36

    Edit: This answer would not transpose the matrix, but rotate it. I didn't read the question carefully in the first place :D

    clockwise and counterclockwise rotation:

        function rotateCounterClockwise(a){
            var n=a.length;
            for (var i=0; i<n/2; i++) {
                for (var j=i; j<n-i-1; j++) {
                    var tmp=a[i][j];
                    a[i][j]=a[j][n-i-1];
                    a[j][n-i-1]=a[n-i-1][n-j-1];
                    a[n-i-1][n-j-1]=a[n-j-1][i];
                    a[n-j-1][i]=tmp;
                }
            }
            return a;
        }
    
        function rotateClockwise(a) {
            var n=a.length;
            for (var i=0; i<n/2; i++) {
                for (var j=i; j<n-i-1; j++) {
                    var tmp=a[i][j];
                    a[i][j]=a[n-j-1][i];
                    a[n-j-1][i]=a[n-i-1][n-j-1];
                    a[n-i-1][n-j-1]=a[j][n-i-1];
                    a[j][n-i-1]=tmp;
                }
            }
            return a;
        }
    
    0 讨论(0)
提交回复
热议问题