I got an array from a single column from google sheet like [[23],[25],[26],[89],[""],[45],[78],[62],[""],[123],[45],[68]] How can I split it with empty values [] and get sums for each sub-array like (163/185/236) or more, cuz array length may be more then 1000 including 20-50 empty values?
I modified the script from the answer. But it doesn't work in my case. I don't understand why?
function getSums(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sh = ss.getSheetByName('TemplateTest');
var r = sh.getRange(1, 1, sh.getLastRow());
var arr = r.getValues(); //log: [[23],[25],[26],[89],[""],[45],[78],[62],[""],[123],[45],[68]]
var sums = [];
var sum = 0;
// iterate through the array
for (var i = 0; i < arr.length; i ++) {
if (arr[i].length == 0 || i == arr.length - 1) {
// empty array, push sum to array and reset
sums.push(sum);
sum = 0;
} else {
// array has values, sum them up and add to sum
sum += arr[i].reduce((a, b) => a + b);
}
}
Logger.log(sums) //log: [16345786212345]
}
Where I'm wrong and how can I fix it?
DEMO:
function getSums(){
//var ss = SpreadsheetApp.getActiveSpreadsheet();
//var sh = ss.getSheetByName('TemplateTest');
//var r = sh.getRange(1, 1, sh.getLastRow());
var arr = [[23],[25],[26],[89],[""],[45],[78],[62],[""],[123],[45],[68]]
//var arr = r.getValues();
var sums = [];
var sum = 0;
// iterate through the array
for (var i = 0; i < arr.length; i ++) {
if (arr[i].length == 0 || i == arr.length - 1) {
// empty array, push sum to array and reset
sums.push(sum);
sum = 0;
} else {
// array has values, sum them up and add to sum
sum += arr[i].reduce((a, b) => a + b, 0);
}
}
console.log(sums) //log: [16345786212345]
}
getSums();