Let's say we want to count the NaN
's in a javascript array. We can use
let arr = [...Array(100)].map( (a,i) => i %10==0 ? NaN : i )
console.log(arr)
> [NaN, 1, 2, 3, 4, 5, 6, 7, 8, 9, NaN, 11, 12, 13, 14, 15, 16, 17, 18, 19, NaN, 21, 22, 23, 24, 25, 26, 27, 28, 29, NaN, 31, 32, 33, 34, 35, 36, 37, 38, 39, NaN, 41, 42, 43, 44, 45, 46, 47, 48, 49, NaN, 51, 52, 53, 54, 55, 56, 57, 58, 59, NaN, 61, 62, 63, 64, 65, 66, 67, 68, 69, NaN, 71, 72, 73, 74, 75, 76, 77, 78, 79, NaN, 81, 82, 83, 84, 85, 86, 87, 88, 89, NaN, 91, 92, 93, 94, 95, 96, 97, 98, 99]
let nans = arr.map( aa => isNaN(aa) ? 1 : 0).reduce((acc,a) => acc+a)
console.log(nans)
> 10
That does work.. but it is a bit challenging to remember the reduce()
machinery every time. Is there a more concise construct by applying a predicate as so:
arr.count( a => isNan(a))
You can have just a single .reduce
where the accumulator is the number of NaNs found so far:
const arr = [...Array(100)].map( (a,i) => i %10==0 ? NaN : i );
const nans = arr.reduce((a, item) => a + isNaN(item), 0);
console.log(nans);
You can filter out the elements that are not NaN.
arr.filter(isNaN).length
//or
arr.filter(function(it){ return isNaN(it); }).length
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With