The countBy
function from the Underscore library is used to group the elements of an array based on a common property. It returns an object with keys that correspond to the property and values that correspond to the number of times that key was found in the array.
index.tsx223 chars8 lines
In the above example, countBy
is called with two arguments. The first argument is the array being counted and the second argument is a function that determines what property of each element to group by. In this case, we are simply grouping by the values themselves.
The resulting object shows that there are two occurrences of each number in the array.
Note that to use the countBy
function, we first need to import the Underscore library using the require
function.
gistlibby LogSnag