简体   繁体   中英

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,

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];
}

You can use the method .pop() that returns and removes the last element from an array.

Make a copy of the original array first and use .pop() method and assign it to a new value.

var myArray = myArrayCopy
var lastArrayObject = myArrayCopy.pop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM