JavaScript equivalent of “nansum” from MATLAB?

200
June 21, 2018, at 3:30 PM

I’m trying to compute the sum of an array with more than 10 000 values in it that contains some NaN. I’ve done a fair bit of research on this and didn’t find an adequate answer.

Using the reduce function works fine if my array doesn’t contain any NaN.

.reduce((pv, cv) => pv+cv, 0)

But is there a quick way to achieve that, like nansum in MATLAB, without looping the entire array, removing the NaN and then computing the sum?

Answer 1

You can check in the reduce function if cv isNaN and substitute 0 if it is:

.reduce((pv, cv) => pv + (isNaN(cv) ? 0 : cv), 0)
Answer 2

You can just remove the NaNs before reducing:

.filter( (n) => !isNaN(n) )
.reduce( (pv, cv) => pv + cv )

I'm not sure if there's a significant difference between this and bhmaker's answer, except that an optimizing compiler might be able to optimize this better.

Rent Charter Buses Company
READ ALSO
Undefined offset ##### [duplicate]

Undefined offset ##### [duplicate]

This question already has an answer here:

151