3 回答
TA贡献1795条经验 获得超7个赞
//reduce的初始值
const initValue = {}
columns.forEach((param, index) => initValue[param] = index == 0 ? '合计' : 0);
data.reduce((total, current, index) => {
//合计累加
const item = {}
columns.forEach((param, index) => {
item[param] = current[index]
//不是name的话,累加
if (index != 0) total[param] += current[index]
})
//把current push到arr
arr.push(item)
//最后一次循环时,把total push到arr
if (index == data.length - 1) arr.push(total)
return total
}, initValue)
TA贡献1776条经验 获得超12个赞
let all = {
name: "合计",
age: 0,
weight: 0
}
data.forEach(item => {
arr.push(
{
name: item[0],
age: item[1],
weight: item[2]
};
all.age = all.age + item[1];
all.weight = all.weight + item[2];
});
arr.push(all);
TA贡献1828条经验 获得超4个赞
const summary = data.reduce((carry, item) => {
arr.push({
[columns[0]]: item[0],
[columns[1]]: item[1],
[columns[2]]: item[2],
});
carry[1] += item[1];
carry[2] += item[2];
}, ['合计', 0 , 0]);
arr.push(summary);
添加回答
举报