简体   繁体   English

如何获取与 javascript 数组中的谓词匹配的元素计数?

[英]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.假设我们要计算 javascript 数组中的NaN 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.这确实有效.. 但每次记住reduce()机制有点挑战。 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:你可以只有一个.reduce ,其中累加器是到目前为止找到的 NaN 的数量:

 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.您可以过滤掉不是 NaN 的元素。

arr.filter(isNaN).length
//or
arr.filter(function(it){ return isNaN(it); }).length

Or while for even bigger...或者更大的while ......

const arr = [...Array(1e6)].map((a, i) => i % 10 == 0 ? NaN : i);

let
  i = arr.length,
  nans = 0;
  
while (i--) {
  nans += isNaN(arr[i]);
}

console.log(nans.toExponential());

 const arr = [...Array(100)].map((a, i) => i % 10 == 0? NaN: i); const count = (arr, predicate) => { let c = 0, i = arr.length; while (i--) c += predicate(arr[i]); return c }; const nans = count(arr, x => isNaN(x)), sevens = count(arr, x => x % 7 === 0); console.log(`nans: ${nans}, sevens: ${sevens}`);

With forEach loop instead of map and reduceforEach循环代替 map 并减少

 const nanCount = (arr, count = 0) => ( arr.forEach((num) => (count += isNaN(num))), count ); const arr = [NaN, 0, 1, 3, NaN]; console.log(nanCount(arr));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM