Captain G
Captain G

Reputation: 3

How to index array's in Google Apps Script?

I was working on this project and I wanted to make a function that displays an element of a specific column.

Now with javascript I can call any element of an array with

Array[i]

But for some reason this doesn't seem to work in Google Spreadsheets.

 var MyFunction(A) {
 return A[1];
 }

This function yields me nothing.

EDIt: I solved it. I used this loop with a sort of double indexing:

for (var i=0; i < 37; i++) {
if (A[0][i] < max && A[0][i] != 0) {
var max = A[0][i];
};
};

A[0][0] is the first element if I select a row vector in spreadsheet. For example, If I select A2:A5 as A, A[0][0] will give me the value of cell A2! Thanks for the help!

Upvotes: 0

Views: 11215

Answers (2)

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17613

It doesn't work that way. You have to first allow access to the spreadsheet then tell Apps Script which Spreadsheet you're working on through openById. After that you can now access the data. Here's a simple code snippet for you. I'm using the standalone mode. There maybe other ways of doing this.

We're going to access this sheet. I've included the index numbers so you can easily understand:

enter image description here

Then we create a function named fetchValue which accepts 2 parameters- the row and the column.

We execute main function which makes calls to fetchValue.

function main(){
   Logger.log("the value returned was "+ fetchValue(1,1) ); //returns las vegas
}

function fetchValue(row,col) {
  var sheet = SpreadsheetApp.openById("SPREADSHEET_ID_HERE");
  var data = sheet.getDataRange().getValues();

   return data[row][col];
}

We then view the Logs if it returned the value of index 1,1 which is las vegas.

enter image description here

Make sure the row and column you pass to fetchValue is within range else it will return errors.

Upvotes: 1

Jack Brown
Jack Brown

Reputation: 5892

Try this instead:

var MyFunction(A) {
 return A[0];
 }

The assumption I making here is you are trying to return the first element in the index. In javascript Array index starts at 0 and not 1.

Upvotes: 1

Related Questions