Transposing a 2D-array in JavaScript

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

    ES6 1liners as :

    let invert = a => a[0].map((col, c) => a.map((row, r) => a[r][c]))
    

    so same as Óscar's, but as would you rather rotate it clockwise :

    let rotate = a => a[0].map((col, c) => a.map((row, r) => a[r][c]).reverse())
    

提交回复
热议问题