Thursday, September 4, 2025
HomeLanguagesJavascriptCollect.js countBy() Method

Collect.js countBy() Method

The countBy() method is used to count the occurrence of values in the collection. This method counts the occurrence of every element.

Syntax:

collect(array).countBy()

Parameters: The collect() method takes one argument that is converted into the collection and then countBy() method is applied on it.

Return Value: This method returns the count of occurrence of values in the collection.

Below example illustrate the countBy() method in collect.js:

Example 1:

Javascript




// It is used to import collect.js library 
const collect = require('collect.js');
  
const num = [0, 1, 1, 2, 3, 4, 4, 5, 5, 5, 5, 5];
const data = collect(num);
  
const total = data.countBy();
  
console.log({ total });


Output:

{
 total: Collection {
   items: { '0': 1, '1': 2, '2': 1, '3': 1, '4': 2, '5': 5 }
 }
}

Example 2:

Javascript




const collect = require('collect.js');
  
const collection = collect([
    'neveropen@gmail.com',
    'aman@gmail.com',
    'krk@gmail.com',
    'abc@gfg.com',
    'demo@gfg.com',
    'hr@geeksforgeeks.org'
]);
  
const counted = collection.countBy(
    email => email.split('@')[1]
);
  
console.log(counted.all());


Output:

{ 'gmail.com': 3, 'gfg.com': 2, 'geeksforgeeks.org': 1 }
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32264 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6629 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6698 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS