Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
    }
like image 915
user1488934 Avatar asked May 18 '13 06:05

user1488934


3 Answers

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]; }); });
}
like image 83
Mogsdad Avatar answered Oct 19 '22 17:10

Mogsdad


You will need to initially assign an array object to each element in the outer result array. There might be more efficient ways, but I would be thinking:

function transposeArray(array){
  var result = [];
  for (var col = 0; col < array[0].length; col++) { // Loop over array cols
    result[col] = [];
    for (var row = 0; row < array.length; row++) { // Loop over array rows
      result[col][row] = array[row][col]; // Rotate
    }
  }
  return result;
}
like image 31
AdamL Avatar answered Oct 19 '22 16:10

AdamL


I have found this way:

function onOpen() {

    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getSheetByName("SEGUNDOA2E");
    var notas = sheet.getRange("G6:AK6").getNotes();

    for (var i = 0; i < 31; i++){
        var nota = notas[0][i];
        var conceptos = sheet.getRange(37+i,7).setValue(nota);
    } 
}

Hope this helps.

like image 1
Mario Moreno Avatar answered Oct 19 '22 18:10

Mario Moreno