ckersch ckersch - 2 months ago 6
Javascript Question

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 invert it to get the following array:

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


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

function invertArray(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?

Answer
var newArray = array[0].map(function(col, i) { 
  return array.map(function(row) { 
    return row[i] 
  })
});

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]