Skip to content
Advertisement

Get last value from an array using Google Apps Script

I need to get last value from an array and I keep getting this error when I use slice

TypeError: Cannot find function slice in object Sun Jul 23 2017 00:00:00 GMT+0100 (BST). (line 15, file

If I use length -1 I get NaN.

This is the code I am using it.

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Data");
  var range = sheet.getDataRange();
  var values = range.getValues();
  var today = new Date(Date.now());
   today.setHours(0,0,0,0);
    Logger.log(today);

var setTotal;
var getToday = values[4].map(Number).indexOf(+today);
Logger.log(getToday);
for (i = 0; i < values.length; i++) {
 var getTotal = values[i][getToday];
       Logger.log(getTotal.slice(-1)[0]); 
 }
}

… and this is the table

full table

So I need when it match the current day (today) to retrieve last value from that array (column) which is the Total for that day.

Thank you!

Kind regards,

Advertisement

Answer

getTotal is always already a singular value.
Also the way you find your column is brittle due to timezones because you normalize only one date.
If you do it with both dates (which needs to be handled safely unless you want to do index constraints) your column finding approach works.

function getTodaysTotal() {
  function toUtcMidnight(date) {
    try {return date.setHours(0,0,0,0);}
    catch(e) {return;}
  }

  var values = SpreadsheetApp
      .getActiveSpreadsheet()
      .getSheetByName("Data")
      .getDataRange()
      .getValues();

  var today = toUtcMidnight(new Date());
  var todaysColumn = values[4].map(toUtcMidnight).map(Number).indexOf(+today);
  var output = values[values.length - 1][todaysColumn];
  return values[values.length - 1][todaysColumn];
}
Advertisement