user1903663
user1903663

Reputation: 1725

How can I create a javascript array froma range in a google sheet?

I want to take a range from a Google spreadsheet, create a javascript array and then pass each item, form the range, into the array.

The values in the range (A5: A10) are, for example, bitcoin-cash, litecoin, ethereum, monero, dash, quantstamp.

My code is as follows:

function appendCoins() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var r = sheet.getRange('A5:A10').getValues();
  var coins = [];
  for (var i=0;i < r.length-1;i++) {
     coins.push(r[0][i]);
    }
    Logger.log(coins)
}

The logger shows me this:

[18-01-10 18:09:07:218 GMT] [bitcoin-cash, null, null, null, null, null]

So the first one is correct, it loops the correct number of times but all the other values are undefined.

Why is this? It should be straightforward. Can anybody help? Thank you.

Upvotes: 0

Views: 92

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074335

getValues returns the range indexed by row, then column. Your range, A5:A10, has five rows and one column. You're treating it as though it had one row and five columns. Swap 0 and i in your code:

function appendCoins() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet1");
  var r = sheet.getRange('A5:A10').getValues();
  var coins = [];
  for (var i=0;i < r.length-1;i++) {
     coins.push(r[i][0]);
  }
  Logger.log(coins)
}

Upvotes: 1

Related Questions