Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get count of elements matching a predicate in a javascript array?

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))

like image 470
WestCoastProjects Avatar asked Mar 02 '23 20:03

WestCoastProjects


2 Answers

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);
like image 59
CertainPerformance Avatar answered Mar 06 '23 12:03

CertainPerformance


You can filter out the elements that are not NaN.

arr.filter(isNaN).length
//or
arr.filter(function(it){ return isNaN(it); }).length
like image 20
Taplar Avatar answered Mar 06 '23 10:03

Taplar