Friday, September 5, 2025
HomeLanguagesJavascriptLodash _.countBy() Method

Lodash _.countBy() Method

The _.countBy method creates an object composed of keys generated from the results of running each element of collection through iteratee. The corresponding value of each key is the number of times the key was returned by iterate. 

Syntax:

_.countBy(collection, [iteratee=_.identity])

Parameters: This method accepts two parameters as mentioned above and described below:

  • collection (Array|Object): This parameter holds the collection to iterate over.
  • [iteratee=_.identity] (Function): This parameter holds the iteratee to transform keys.

Return Value: This method is used to returns the composed aggregate object.

 Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file. 

javascript




// Requiring the lodash library
const _ = require("lodash");
     
// Original array
 
var obj1 = ([6.1, 4.2, 6.3, 5, 7.9, 5.3, 5.1, 7.3 ]);
 
// Use of _.countBy() method
let y = _.countBy(obj1, Math.floor);
     
 
// Printing the output
console.log(y);


Output:

{ '4': 1, '5': 3, '6': 2, '7':2 }

Example 2: 

javascript




// Requiring the lodash library
const _ = require("lodash");
     
// Original array
 
var obj1 = (['one', 'two', 'three', 'five', 'eleven', 'twelve'] );
 
// Use of _.countBy()
// method
  
// The `_.property` iteratee shorthand.
let y = _.countBy(obj1, 'length');   
 
// Printing the output
console.log(y);


Output:

{ '3': 2, '4': 1, '5': 1, '6':2 }

Example 3: 

javascript




// Requiring the lodash library
const _ = require("lodash");
     
// Original array
 
var obj1 = (['tee', 'cee', 'dee', 'bee', 'eee' ]);
var obj2 = (['q', 'r', 's', 'p' ]);
 
// Use of _.countBy() method
  
// The `_.property` iteratee shorthand.
let x = _.countBy(obj1, 'length');   
let y = _.countBy(obj2, 'length');
 
// Printing the output
console.log(x);
console.log(y);


Output:

{ '3': 5 }
{ '1': 4 }

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.

RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS