Transposing a 2D-array in JavaScript

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

    Since nobody so far mentioned a functional recursive approach here is my take. An adaptation of Haskell's Data.List.transpose.

    var transpose = as => as.length ? as[0].length ? [ as.reduce( (rs,a) => a.length ? ( rs.push(a[0])
                                                                                       , rs
                                                                                       )
                                                                                     : rs
                                                                , []
                                                                )
                                                     , ...transpose(as.map(a => a.slice(1)))
                                                     ]
                                                   : transpose(as.slice(1))
                                    : [],
        mtx       = [[1], [1, 2], [1, 2, 3]];
    
    console.log(transpose(mtx))
    .as-console-wrapper {
      max-height: 100% !important
    }

提交回复
热议问题