Lodash _.countBy() Method

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:

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

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output:

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

Example 2:

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output:

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

Example 3:

javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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);

chevron_right


Output:

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

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

full-stack-img




My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.