Underscore.js | countBy() with Examples
The _.countBy() function is used to sort a list into groups and returns a count for the number of objects in each group. It works by matching the value of each element to the other. If they matches then the count of one collection increases by 1 otherwise the count of another collections/groups which has that value increases by 1. It can also pass a function based on who’s result will collect the elements and increase the count of each group. It can match both on the basis of number and also by string.
_.countBy(list, iteratee, [context])
Parameters: This function accepts three parameters as mentioned above and described below:
- List: This parameter is used to hold the list of items.
- Iteratee: This parameter is used to hold the test condition.
- Context: The text content which need to display.
Return values: It returns the collections as the different arrays.
Passing Math.ceil() function to the _.countBy() function: The _.countBy() function takes the element from the list one by one and pass it to the other function mentioned here. Here the function is taking the ceil of each number and returning it’s values. So, all the value of the array are counted one by one after their ceil has been taken and then counted according to whether they are same or different.
Using length() in the _.countBy() function: Passing the array elements to the countBy() function. Then, find out the length of each element and make collections of the lengths that are same. Finally, display the count of each collection with the respective lengths along the left.
Using one property of the array passed in the _.countBy() function: First declare the array (here array is ‘arr’). Choose one condition on which need to count like here ‘prop3’. Then the elements which have the same value in the ‘prop3’ will be grouped in 1 collection. The final result will contain the prop3 in the left side along with their count on the right. Like here in prop3, “Geeks” is coming two times, so it’s count will be 2. Console.log the final answer.
Passing ‘date’ as property of the array to the _.countBy() function together: First define an array with one property as ‘date’ of the format ‘dd-mm-yy’. Then pass the array and the ‘date’ property to the _.countBy() function. The elements having the same date will be grouped as one collection and then the count of each group will be displayed in the result.
Note: These commands will not work in Google console or in Firefox as for these additional files need to be added which they didn’t have added. So, add the given links to your HTML file and then run them.