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);
添加回答
舉報