Baka
Baka

Reputation: 759

How To Add values to two-dimensional array with for loops using Google Apps Script

Could someone show me some simple examples to add values with for loops to a two-dimensional array?

My totally wrong test script is below.

Expected behavior:

wholeValues[[0],[0]] = 0, wholeValues[[0],[1]] = 1, wholeValues[[0],[2]] = 2,

wholeValues[[1],[0]] = 0, wholeValues[[1],[1]] = 1, wholeValues[[1],[2]] = 2 .....

function test() {
  var wholeValues = [[],[]];
  var value = [];
    for (var i = 0; i < 5; i++){                     
       for (var j = 0; j < 3; j++) {           
           wholeValues[[i],[j]] = value[j];
       }
    }

  Logger.log(wholeValues[[0],[1]]);
}

Upvotes: 2

Views: 8220

Answers (1)

shabnam bharmal
shabnam bharmal

Reputation: 584

Hope this could help.

function test() {

  //2d array
  var wholeValues = [];


  for (var i = 0; i < 5; i++){  

    //create a 1D array first with pushing 0,1,2 elements with a for loop
    var value = [];
    for (var j = 0; j < 3; j++) {           
      value.push(j);
    }
    //pushing the value array with [0,1,2] to thw wholeValues array. 
    wholeValues.push(value);
  } // the outer for loop runs five times , so five the 0,1,2 with be pushed in to thewholevalues array by creating wholeValues[0][0],wholeValues[0][1]...till..wholeValues[4][2]

  Logger.log(wholeValues[0][1]);
}

Upvotes: 4

Related Questions