47

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}]
swelet
  • 8,192
  • 5
  • 33
  • 45

3 Answers3

58

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);
Gunar Gessner
  • 2,331
  • 23
  • 23
  • The official documentation doesn't do a good job of explaining the possibilities you are showing here, so thank you. I still think this answer could be improved if the example code were explained, though. – Daniel Kaplan Jan 25 '23 at 00:38
47

Below you can find an easy way to achieve that using the filter method:

var b = _.filter(a, function(o) { if (o.a < 4) return o }).length;
JesusTinoco
  • 11,288
  • 5
  • 30
  • 23
25

You can use _.countBy:

const count = _.countBy(arr, o => o.a < 4).true

Ahmed Ismail
  • 912
  • 11
  • 21