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?
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.
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).
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).
output = array[0].map((_, colIndex) => array.map(row => row[colIndex]));
map
calls a providedcallback
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With