Transposing a 2D-array in JavaScript
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]
here is my implementation in modern browser (without dependency):
transpose = m => m[0].map((x,i) => m.map(x => x[i]))