在Appsscript中使用reduce Methode和Accumulator对2D数组中的值求和



到目前为止,我面临以下挑战,我知道如何使用Reduce方法对一个dim数组中的所有值求和。

var sum = array.reduce((accumulator, currentValue) => {
return accumulator + currentValue; }); 

但是如何在2d数组上使用此方法?例如,我想对5中的所有项目求和。列。

不完全确定这是否是您想要的

function sumfive() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet0');
const [h, ...v] = sh.getDataRange().getValues();
let sum = v.reduce((a, r) => {
let row = 0;
r.forEach((c, i) => {
if (i > 4) { row += Number(c); }
});
a.sum += row;
return a;
}, { sum: 0, getSum: function () { return this.sum; } }).getSum();
Logger.log(sum);
}

数据:

COL10>td style="ext-align:left;">20>td style="text-align:left;">223<24>26
COL1COL8COL9COL11COL17COL18COL19COL20
19101120
21011121321
31112131422
41213141523
51314151624
61415161725
71516171819
8161718192021222324252627
917181928
1018192029
1119202130
1220212231
1321222332
1422232433
1523242534
1624252635
1725262736
1826272837
1927282938
2028293039

最新更新