Google Spreadsheet Script - How to Transpose / Rotate Multi-dimensional Array?

user1488934 picture user1488934 · May 18, 2013 · Viewed 20.2k times · Source

I'm trying to create a function that takes in any array and transpose it so that rows turns to columns and columns to rows.

Not sure what I've done wrong or missing but keep getting this message once the array is pass through....

TypeError: Cannot set property "0.0" of undefined to "xxxxxx".

the error is on line

result[row][col] = array[col][row]; // Rotate

Any pointer would be much appreciated.

function transposeArray(array){
        var result = [];
        for(var row = 0; row < array.length; row++){ // Loop over rows
          for(var col = 0; col < array[row].length; col++){ // Loop over columns
            result[row][col] = array[col][row]; // Rotate
          }
        }
        return result;
    }

Answer

Mogsdad picture Mogsdad · May 23, 2013

My personal favourite is this gist:

function transpose(a)
{
  return Object.keys(a[0]).map(function (c) { return a.map(function (r) { return r[c]; }); });
}