Transposing a 2D-array in JavaScript

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

    I think this is slightly more readable. It uses Array.from and logic is identical to using nested loops:

    var arr = [
      [1, 2, 3, 4],
      [1, 2, 3, 4],
      [1, 2, 3, 4]
    ];
    
    /*
     * arr[0].length = 4 = number of result rows
     * arr.length = 3 = number of result cols
     */
    
    var result = Array.from({ length: arr[0].length }, function(x, row) {
      return Array.from({ length: arr.length }, function(x, col) {
        return arr[col][row];
      });
    });
    
    console.log(result);

    If you are dealing with arrays of unequal length you need to replace arr[0].length with something else:

    var arr = [
      [1, 2],
      [1, 2, 3],
      [1, 2, 3, 4]
    ];
    
    /*
     * arr[0].length = 4 = number of result rows
     * arr.length = 3 = number of result cols
     */
    
    var result = Array.from({ length: arr.reduce(function(max, item) { return item.length > max ? item.length : max; }, 0) }, function(x, row) {
      return Array.from({ length: arr.length }, function(x, col) {
        return arr[col][row];
      });
    });
    
    console.log(result);

提交回复
热议问题