Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax: 
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Counting Numbers by Even and Odd:
4.2.
JavaScript
4.3.
Categorizing Strings by Length:
4.4.
JavaScript
4.5.
Counting Objects by Property:
4.6.
JavaScript
4.7.
Counting with Custom Function:
4.8.
JavaScript
5.
Frequently Asked Questions 
5.1.
Can _.countBy() handle mixed data types in a collection?
5.2.
How does _.countBy() differ from _.groupBy()?
5.3.
Is _.countBy() efficient for large collections?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.countBy() Method

Author Pallavi singh
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Effective data categorization and counting are pivotal in many programming scenarios. The Lodash library enriches JavaScript with the _.countBy() method, a versatile function for grouping and counting collection elements based on a specified criterion. 

Lodash _.countBy() Method

This article will thoroughly examine the _.countBy() method, illustrating its syntax, use cases, and practicality through examples and FAQs.

Why This Function is Used

The _.countBy() function is used for categorizing elements in a collection (like an array or object) and counting them based on a specified criterion. This is particularly useful in data analysis and manipulation tasks where understanding the distribution of data is crucial. It helps in identifying patterns, frequencies of occurrences, and categorizing data efficiently, thus simplifying complex data processing tasks.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Syntax, Parameter and Return Value

Syntax: 

_.countBy(collection, [iteratee=_.identity])

Parameters:

  • collection (Array|Object): The collection to iterate over.
     
  • [iteratee=_.identity] (Function): The iteratee to transform keys.

Return Value: 

(Object) - Returns the composed aggregate object.

Examples 

Counting Numbers by Even and Odd:

  • JavaScript

JavaScript

var _ = require('lodash');

var numbers = [1, 2, 3, 4, 5, 6];

var countByEvenOdd = _.countBy(numbers, num => num % 2 === 0 ? 'even' : 'odd');

console.log(countByEvenOdd);

Output:

{ 'odd': 3, 'even': 3 }


This example demonstrates counting numbers based on whether they are even or odd.

Categorizing Strings by Length:

  • JavaScript

JavaScript

var words = ['sky', 'wood', 'forest', 'cliff', 'castle', 'river'];

var countByLength = _.countBy(words, 'length');

console.log(countByLength);

 Output: 

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

Here, strings are categorized and counted based on their length.

Counting Objects by Property:

  • JavaScript

JavaScript

var objects = [{ 'type': 'fruit', 'name': 'apple' }, 

              { 'type': 'vegetable', 'name': 'carrot' },

              { 'type': 'fruit', 'name': 'banana' }];

var countByType = _.countBy(objects, 'type');

console.log(countByType);

Output: 

{ 'fruit': 2, 'vegetable': 1 }


An example showing how to count objects based on a shared property.

Counting with Custom Function:

  • JavaScript

JavaScript

var items = [1.3, 2.1, 2.4];

var countByIntegerPart = _.countBy(items, Math.floor);

console.log(countByIntegerPart);

Output: 

{ '1': 1, '2': 2 }


Demonstrates using a custom function to determine the counting criterion.

Frequently Asked Questions 

Can _.countBy() handle mixed data types in a collection?

Yes, it can categorize and count mixed data types, provided the iteratee function can handle them appropriately.

How does _.countBy() differ from _.groupBy()?

While _.groupBy() groups elements without counting, _.countBy() categorizes elements and provides a count for each category.

Is _.countBy() efficient for large collections?

_.countBy() is generally efficient for large collections, but its performance may vary depending on the complexity of the iteratee function.

Conclusion

Lodash's _.countBy() method is a powerful and flexible tool for categorizing and counting elements in a collection based on specific criteria. It aids in data analysis and manipulation by providing insights into the distribution and frequency of data elements. This method exemplifies the utility of Lodash in simplifying and enhancing data handling in JavaScript.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Lodash _.find() Method
Next article
Lodash _.differenceWith() Method
Live masterclass