how to use the countby function from the underscore library in javascript

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.tsx
const _ = require('underscore');

const scores = [1, 2, 3, 4, 5, 5, 4, 3, 2, 1];
const countedScores = _.countBy(scores, (score) => score);

console.log(countedScores);
// Output: { '1': 2, '2': 2, '3': 2, '4': 2, '5': 2 }
223 chars
8 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