到目前为止,我面临以下挑战,我知道如何使用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);
}
数据:
COL1 | COL8 | COL9 | COL10COL11 | COL17 | COL18 | COL19 | COL20 | |||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
1 | 9 | 10 | 11 | 20 | ||||||||
2 | 10 | 11 | 12 | 13 | 21 | |||||||
3 | 11 | 12 | 13 | 14 | 22 | |||||||
4 | 12 | 13 | 14 | 15 | 23 | |||||||
5 | 13 | 14 | 15 | 16 | 24 | |||||||
6 | 14 | 15 | 16 | 17 | 25 | |||||||
7 | 15 | 16 | 17 | 18 | 19 | >td style="ext-align:left;">20>td style="text-align:left;">223<24>26|||||||
8 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 |
9 | 17 | 18 | 19 | 28 | ||||||||
10 | 18 | 19 | 20 | 29 | ||||||||
11 | 19 | 20 | 21 | 30 | ||||||||
12 | 20 | 21 | 22 | 31 | ||||||||
13 | 21 | 22 | 23 | 32 | ||||||||
14 | 22 | 23 | 24 | 33 | ||||||||
15 | 23 | 24 | 25 | 34 | ||||||||
16 | 24 | 25 | 26 | 35 | ||||||||
17 | 25 | 26 | 27 | 36 | ||||||||
18 | 26 | 27 | 28 | 37 | ||||||||
19 | 27 | 28 | 29 | 38 | ||||||||
20 | 28 | 29 | 30 | 39 |