Open In App

Collect.js countBy() Method

Last Updated : 25 Nov, 2020
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

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([
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]',
    '[email protected]'
]);

const counted = collection.countBy(
    email => email.split('@')[1]
);

console.log(counted.all());

Output:

{ 'gmail.com': 3, 'gfg.com': 2, 'geeksforgeeks.org': 1 }

Similar Reads