The lodash _.countBy method

Every now and then I like to play around with one of the methods in lodash such as the _.countBy collection method that I will be writing about in this post. I do this just because lodash is still very popular, and it makes sense to play around with it now and then, and maybe compare where is there with what there is to work with in core javaScript itself.

The _.countBy method returns a new object with keys, and values generated from a given method.

Basic count by Example

For a basic demo of _.countBy I just made an array of objects, and used countBy to make an object of true, and false properties that is a count of how many objects meet the condition that I defined in the method that I gave it, along with the array of objects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var arr = [
{
username: 'john',
score: 37
}, {
username: 'jake',
score: 50
}, {
username: 'bill',
score: 20
}
];
var obj = _.countBy(arr, function (rec) {
return rec.score >= 50;
});
console.log(obj.false); // 2
console.log(obj.true); // 1

So it seems that this can be a useful method to be aware of to quickly find out a count of how many elements in an array meet a given set of conditions, and how many do not. I am not aware of anything in corejs that does this, so thins may be one of the methods in lodash to which there is not a direct native equivalent.

Quickly get a count of word length for each word in an array

The ‘_.property’ iteratee shorthand can be used to get an object of keys where each key is a word length, and each value is how many times a word of that length appears in the collection.

1
2
console.log(_.countBy(['foo', 'man', 'chew','happy','bar'], 'length'));
// {3: 3, 4: 1, 5: 1}

The following will give the same result

1
2
3
4
console.log(_.countBy(['foo', 'man', 'chew','happy','bar'], function(str){
return str.length;
}));
// {3: 3, 4: 1, 5: 1}

Conclusion

This _.countBy method might come in handy for some situations in which I quickly want to make an object that has keys, and values that are the result of some kind of condition. This makes _.countBy one of the methods in lodash to be aware of to make quick work of any kind of situation where it would come in handy.