user4535384
user4535384

Reputation: 27

How to put data into a 2D array in google script / javascript?

I am trying to make an array such that it looks like

[[name,result],[name,result],[name,result],......[name,result]]

with the for loop changing the name and result.

I am getting this error: TypeError: Cannot set property '0' of undefined at array[i][0] = name;

Code:

function one(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("123aaa");
  var num_of_samples = 5;
  var array=[[],[]];

  for(i=1; i <= num_of_samples; i++){

    var name = sheet.getRange(2*i+6,2).getValue();
    var result = sheet.getRange(2*i+7,2).getValue();
    array[i][0] = name;
    array[i][1] = result;
  }
  Logger.log(array);

}

Upvotes: 0

Views: 87

Answers (1)

Cooper
Cooper

Reputation: 64042

function one() {
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName("123aaa");
  var num_of_samples = 5;
  var array = [];
  for (i = 1; i <= 5; i++) {
    array.push([`Name${i}`, `Result${i}`]);
  }
  Logger.log(array);
}

Execution log
3:06:45 PM  Notice  Execution started
3:06:46 PM  Info    [[Name1, Result1], [Name2, Result2], [Name3, Result3], [Name4, Result4], [Name5, Result5]]
3:06:46 PM  Notice  Execution completed

Upvotes: 2

Related Questions