0

my code below works to add all the values together and displays the total, when I try an divide the items (/ val.flowers) it outputs NaN.

trimPerFlowerA(){        
        let lineA = this.model.processed.filter(val => val.originatingLine === 'A');
            if(lineA.length > 0)
               return lineA.map(val => { 
                   return (val.trimA+val.trimB+val.trimC+val.flowerOilGrade/val.flowers)
                   }).reduce((a,b) => a+b,0);
            return 0;
    }
Mike
  • 129
  • 1
  • 9
  • 2
    Difficult to say without seeing `lineA`. – Mamun Nov 15 '19 at 14:04
  • 1
    It would suggest that `val.flowers` is zero or undefined. – John Nov 15 '19 at 14:04
  • Or not a number or can't be parsed as number – Timur Gilauri Nov 15 '19 at 14:05
  • 2
    It means that one of the things involved in the calculation is the value `NaN` or is a non-number that, when implicitly parsed, can't be parsed as a number. At that point, since any math operation on `NaN` results in `NaN`, it spreads throughout the computation. The only way to know why that is is to look at the values in the variables. Set a breakpoint on it, and check them. – T.J. Crowder Nov 15 '19 at 14:07
  • 1
    @John - If it were zero, the result would be `Infinity`, not `NaN`. (JavaScript handles divide by zero by using `Infinity`.) – T.J. Crowder Nov 15 '19 at 14:10
  • @T.J. Crowder. Thanks for the heads-up. I am not especially happy that a divide by zero is represented as Infinity but these answers are slightly reassuring. https://stackoverflow.com/questions/18838301/in-javascript-why-does-zero-divided-by-zero-return-nan-but-any-other-divided-b – John Nov 15 '19 at 23:50

1 Answers1

0

If I were to place a bet, I would say that you have some undefined lurking around.

This problem really depends on your input data and therefore on the contents of this.model.processed. On a general basis, a number of calculations in JavaScript can result in NaN.

Some typical cases are:

  • "A"/0
  • "A"/"B"
  • 0/"A"
  • 0/0
  • NaN/0
  • 0/NaN
  • NaN/NaN
  • undefined/10
  • 1/undefined

However, in your specific case it's also possible that the problem is not in the division but in the sum within the (val.trimA+val.trimB+val.trimC+val.flowerOilGrade/val.flowers) expression. In particular, you can have NaN also for:

  • NaN+1/10
  • undefined+1

And all similar expressions.

I would recommend putting some breakpoints around and verify the individual values. If the amount of entries doesn't lend itself to breakpoints, try and put some console.log on those same values and then check them. This should allow you to pinpoint the specific value (or values) that cause the output to be NaN.

Also, once you found the issue, you will probably want to cover your base by adding unit tests working against both valid and invalid input data.

Filippo Possenti
  • 1,300
  • 8
  • 18