"Count where" in a collection

swelet picture swelet · Feb 22, 2016 · Viewed 26.9k times · Source

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}]

Answer

JesusTinoco picture JesusTinoco · Feb 22, 2016

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;