Skip to content
Related Articles

Related Articles

Improve Article

Lodash _.countBy() Method

  • Last Updated : 01 Sep, 2020

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

Syntax:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

_.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.




My Personal Notes arrow_drop_up
Recommended Articles
Page :