Open In App

Lodash _.countBy() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.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
 
let 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: In this example, the code uses Lodash’s _.countBy method with the _.property iteratee shorthand to count the number of elements in an array based on their string length and displays the count results in the console.

javascript




// Requiring the lodash library
const _ = require("lodash");
     
// Original array
 
let 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: In this example, the code utilizes Lodash’s _.countBy method with the _.property iteratee shorthand to count elements in two arrays based on their string length and displays the count results for each array in the console.

javascript




// Requiring the lodash library
const _ = require("lodash");
     
// Original array
 
let obj1 = (['tee', 'cee', 'dee', 'bee', 'eee' ]);
let 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.



Last Updated : 13 Nov, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads