Transposing a 2D-array in JavaScript

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

提交回复
热议问题