使用lodash,有条件地计算集合中对象数量的好方法是什么?说我想计算
的对象数量a < 4
在以下集合中
[{a : 1}, {a : 2}, {a : 3}, {a : 4}, {a : 5}, {a : 6}]
答案 0 :(得分:32)
您可以在下面找到使用filter方法实现该目标的简便方法:
var b = _.filter(a, function(o) { if (o.a < 4) return o }).length;
答案 1 :(得分:29)
您可以使用sumBy
:
const count = _.sumBy(
objects,
({ a }) => Number(a < 4)
);
或者,您可以使用lodash/fp
:
const count = _.sumBy(_.flow(_.get('a'), _.lt(4), Number), objects);
答案 2 :(得分:0)
另一个解决方案是使用_.countBy:
const count = _.countBy(arr, function (o) { return o.a < 4}).true