gpt4 book ai didi

angular - 如何在Angular 10中获取表中多列的平均值

转载 作者:行者123 更新时间:2023-12-04 07:57:22 24 4
gpt4 key购买 nike

我有计算表上所有列中 json 数据总和的函数。我想获得每列的平均值,但最终得到 NaN 或无穷大,我做错了什么?
这是我获取总和的实现

getSum(columnNumber) {
let sum = 0;
const columnNumberToPropertyMap = [
"id",
"teamNumber",
"rural",
"completed",
"entirehouseholdabsent",
"postponed",
"refused",
"vacant",
"dwelling"
];
const property = columnNumberToPropertyMap[columnNumber];
return this.rural.reduce((acc, curr) => {
//const adder = Number(curr[property]) || 0;
const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
return sum;
}, 0).toFixed(2);
}
这给了我列中所有行的总和。
我如何尝试获得每列的平均值
 getSum(columnNumber) {
let sum = 0;
let average = 0;

const columnNumberToPropertyMap = [
"id",
"teamNumber",
"rural",
"completed",
"entirehouseholdabsent",
"postponed",
"refused",
"vacant",
"dwelling"
];
const property = columnNumberToPropertyMap[columnNumber];
return this.rural.reduce((acc, curr) => {
//const adder = Number(curr[property]) || 0;
const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
average = (sum)/adder;
return average ;
}, 0).toFixed(2);
}
我最终在每列的下方得到 NaN 或无穷大,我假设

average = total of each column / no of items on each column

最佳答案

要查找平均值,您只需调用 getSum然后除以行数。因此,实现将是这样的:

getAverage(columnNumber) {
let sum = getSum(columnNumber);
let count = this.rural.length;
return sum / count;
}
或者,在一行中, return getSum(columnNumber)/this.rural.length;

关于angular - 如何在Angular 10中获取表中多列的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66634021/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com