Transposing a 2D-array in JavaScript

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

    Neat and pure:

    [[0, 1], [2, 3], [4, 5]].reduce((prev, next) => next.map((item, i) =>
        (prev[i] || []).concat(next[i])
    ), []); // [[0, 2, 4], [1, 3, 5]]
    

    Previous solutions may lead to failure in case an empty array is provided.

    Here it is as a function:

    function transpose(array) {
        return array.reduce((prev, next) => next.map((item, i) =>
            (prev[i] || []).concat(next[i])
        ), []);
    }
    
    console.log(transpose([[0, 1], [2, 3], [4, 5]]));
    

    Update. It can be written even better with spread operator:

    const transpose = matrix => matrix.reduce(
        ($, row) => row.map((_, i) => [...($[i] || []), row[i]]), 
        []
    )
    

提交回复
热议问题