Transposing a 2D-array in JavaScript

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

    A library-free implementation in TypeScript that works for any matrix shape that won't truncate your arrays:

    const rotate2dArray = (array2d: T[][]) => {
        const rotated2d: T[][] = []
    
        return array2d.reduce((acc, array1d, index2d) => {
            array1d.forEach((value, index1d) => {
                if (!acc[index1d]) acc[index1d] = []
    
                acc[index1d][index2d] = value
            })
    
            return acc
        }, rotated2d)
    }
    

提交回复
热议问题