[Fixed] How to get average of multiple columns in a table in Angular 10

Issue

I have function that calculates sum of json data in all columns on my tables. I want to get the average of each column, but I end up getting NaN or infinity, What am I doing wrong?

This is my implementation for getting 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 = Number(curr[property]) || 0;
      const adder = isNaN(Number(curr[property])) ? 0 : Number(curr[property]);
      sum = acc + adder
      return sum;
    }, 0).toFixed(2);
  }

this gives me the sum of all the rows in the column.

How am trying to get 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 = 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);
      }

I end up with NaN or infinity at the below of each column, am assuming

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

Solution

To find the average, you can simply call getSum and then divide it by the number of rows. So, implementation would be like this:

getAverage(columnNumber) {
    let sum = getSum(columnNumber);
    let count = this.rural.length;
    return sum / count;
}

Or, in one line, return getSum(columnNumber)/this.rural.length;

Leave a Reply

(*) Required, Your email will not be published