Transposing a 2D-array in JavaScript

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

    If you have an option of using Ramda JS and ES6 syntax, then here's another way to do it:

    const transpose = a => R.map(c => R.map(r => r[c], a), R.keys(a[0]));
    
    console.log(transpose([
      [1, 2, 3, 4],
      [5, 6, 7, 8],
      [9, 10, 11, 12]
    ])); // =>  [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]

提交回复
热议问题