Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transposing a 2D-array in JavaScript

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 array:

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

It's not difficult to programmatically do so using loops:

function transposeArray(array, arrayLength){
    var newArray = [];
    for(var i = 0; i < array.length; i++){
        newArray.push([]);
    };

    for(var i = 0; i < array.length; i++){
        for(var j = 0; j < arrayLength; j++){
            newArray[j].push(array[i][j]);
        };
    };

    return newArray;
}

This, however, seems bulky, and I feel like there should be an easier way to do it. Is there?

like image 500
ckersch Avatar asked Jul 02 '13 14:07

ckersch


People also ask

How do you transpose a 2D array?

The transpose of a matrix (2-D array) is simply a flipped version of the original matrix (2-D array). We can transpose a matrix (2-D array) by switching its rows with its columns.

Can you have a 2D array in JavaScript?

Assuming a somewhat pedantic definition, it is technically impossible to create a 2d array in javascript. But you can create an array of arrays, which is tantamount to the same. FYI... when you fill an array with more arrays using var arr2D = new Array(5).

How do you transpose a matrix into an array?

NumPy Matrix transpose() – Transpose of an Array in Python The transpose of a matrix is obtained by moving the rows data to the column and columns data to the rows. If we have an array of shape (X, Y) then the transpose of the array will have the shape (Y, X).


1 Answers

output = 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]

like image 59
Fawad Ghafoor Avatar answered Oct 05 '22 15:10

Fawad Ghafoor