0
votes

I am struggling with a 2D array in Google Apps Spreadsheet script.

I have a range in a spreadsheet, like so:

   Col A -   Col B
 1   1   -   apple
 2   2   -   pear
 3   3   -   banana
 4   4   -   pineapple
 5   5   -   strawberry

(Sorry, don't have enough rep yet to post an image. Column A holds a number starting at 1 (like a index), and column B holds a fruit)

As I understand, in the script, I read this range into an array like so:

var vcArray = sheet.getRange("A1:B5").getValues();

What I now want to do, is loop through this array, and pull out only the fruit names. This is what I have so far:

  for (var i = 0; i <= 5; i++) {
    var j=1;
    Logger.log("vcarray = " + vcArray[i][1]);
  }

but, I get the following error:

TypeError: Cannot read property "1" from undefined. (line 15, file "Code")

Do I even need Column A?

1

1 Answers

0
votes

Need a slight change:

...
//for (var i = 0; i <= 5; i++)
for (var i = 0; i < 5; i++)
  var j=1;
  Logger.log("vcarray = " + vcArray[i][1]);
}
...

Spreadsheets count from 1, arrays count from 0, that's why vcArray[5] is undefined.