Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Count where" in a collection

Tags:

lodash

Using lodash, what would be a good way to count the number of objects in a collection conditionally? Say I wanted to count the number of objects where

a < 4 

in the following collection

[{a : 1}, {a : 2}, {a : 3}, {a : 4}, {a : 5}, {a : 6}] 
like image 276
swelet Avatar asked Feb 22 '16 19:02

swelet


1 Answers

Solution

You can use countBy:

const total = _.countBy(     array,     ({ a }) => a < 4 ? 'lessThanFour' : 'greaterThanFour'   ).lessThanFour 

Alternative

Using sumBy:

const total = _.sumBy(   array,   ({ a }) => Number(a < 4) ); 

And here's the same but with lodash/fp:

const count = _.sumBy(_.flow(_.get('a'), _.lt(4), Number), objects); 
like image 134
Gunar Gessner Avatar answered Sep 19 '22 19:09

Gunar Gessner