plotly/react-pivottable

How to remove Remove Zero From Average Calculation ?

ayarhlaine opened this issue · 2 comments

How to override Aggregators for average

Is there any way to remove zero values from average calculation?
I have the data like that: Name, Exam and Score.

Screen Shot 2020-12-14 at 5 14 02 PM

But, when I trying to look average calculation for specific user, I don't got my expected average score like that:

Screen Shot 2020-12-14 at 5 16 33 PM

Expectation

Average = 90/1 = 90 (removed zero values)

Actual

Average = (90+0+0) / 3 = 30.00

Could I get any reference to override average method?

Code Sandbox Link

https://codesandbox.io/s/competent-thunder-gqe94?file=/src/App.js:363-368

Already solved by writing own aggregator for average calculation 🔥 🔥 🔥.

Screen Shot 2020-12-17 at 7 11 39 PM

import { numberFormat } from "react-pivottable/Utilities";
export function averageAggregator() {
  return function ([attr]) {
    return function () {
      return {
        count: 0,
        total: 0.0,
        push(record) {
          const currentValue = parseFloat(record[attr]);
          if (isNaN(currentValue)) {
            return;
          }
          if (currentValue > 0) {
            this.count += 1;
            this.total += currentValue;
          }
        },
        value() {
          if (this.count === 0 || this.total === 0) {
            return 0;
          }
          return this.total / this.count;
        },
        format: numberFormat(),
        numInputs: typeof attr !== "undefined" ? 0 : 1
      };
    };
  };
}

Also added unit tests for this as well!

Screen Shot 2020-12-17 at 7 13 58 PM

Can close or make open with your choice. Thanks for supporting react-pivottable.