Currently, I have a function that successfully calculates the sum of JSON data in all columns on my tables. However, my attempt to get the average of each column is resulting in NaN or infinity. What could be the issue here?
Here is my current implementation for obtaining the sum:
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 = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
return sum;
}, 0).toFixed(2);
}
This code successfully gives me the sum of all the rows in the column.
Now, here is how I'm attempting to find the average of each column:
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 = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
sum = acc + adder
average = (sum) / adder;
return average;
}, 0).toFixed(2);
}
Unfortunately, I keep encountering NaN or infinity at the bottom of each column. The formula I am using is 'average = total of each column / no of items on each column'.