The countBy
function from lodash creates an object composed of keys generated from the results of running each element through an iteratee function. The corresponding value of each key is the number of times the key was generated from the iteratee function. Here's how to use it:
index.tsx931 chars27 lines
In the first example, countBy
counts how many times each letter appears in the string "hello world"
. The resulting object has keys for each letter and values for how many times each letter appears in the string.
In the second example, countBy
counts how many times each fruit appears in the array fruits
. The resulting object has keys for each fruit and values for how many times each fruit appears in the array.
In the third example, countBy
counts how many times each age appears in the array of people
objects. The resulting object has keys for each age and values for how many times each age appears in the array of objects.
gistlibby LogSnag