Simon Breton
Simon Breton

Reputation: 2876

How can I extract specific values from an array ?

I have this variable :

var test = sheet1.getRange(sheet1.getLastRow(),1,1,sheet1.getLastColumn()).getValues();

Which return me the following result :

[[data0, data1, data2, data3, data4, etc...]]

Can I convert this array into an array or array [[data0],[data1],[data2],[data3],etc...] so I can do something like this test[1][3] so select data1 and data3 ? Is this the best solution ? If yes, how can I do this ? If no what's the best solution.

Upvotes: 0

Views: 635

Answers (1)

ReyAnthonyRenacia
ReyAnthonyRenacia

Reputation: 17651

Use getDataRange().getValues() to get all the values of the sheet first and assign that to a variable. You can now access that variable like a 2D array. Here's a short snippet to show you.

 function main(){
   Logger.log("the value returned was "+ fetchValue(1,1) ); //will fetch the value at index 1,1
}

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

   return data[row][col];
}

The fetchValue method we've created extracts the value from the specified row,col index. Check my answer here if you want additional reference.

Upvotes: 1

Related Questions