🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Introduction
Counting the occurrences of elements in an array is a common task in programming. JavaScript provides several ways to accomplish this, such as using reduce(), filter(), and forEach(). This guide will walk you through writing a JavaScript program to count the occurrences of each element in an array or a specific element.
Problem Statement
Create a JavaScript program that:
- Accepts an array of integers or strings.
- Counts the occurrences of a specific element or all elements.
- Displays the count.
Example:
Input:
[1, 2, 2, 3, 4, 4, 5], count occurrences of2Output:
2 appears 2 timesInput:
['apple', 'banana', 'apple', 'orange']Output:
'apple' -> 2'banana' -> 1'orange' -> 1
Solution Steps
- Initialize the Array: Provide an array with some duplicate elements.
- Count Occurrences of a Specific Element: Use the
filter()method to count occurrences of a single element. - Count Occurrences of All Elements: Use
reduce()to count the occurrences of each unique element. - Display the Result: Output the count for the specific element or all elements.
JavaScript Program
Method 1: Count Occurrences of a Specific Element Using filter()
// JavaScript Program to Count Occurrences of a Specific Element in an Array
// Author: https://www.rameshfadatare.com/
function countOccurrences(arr, element) {
// Step 1: Use filter to count occurrences of the specific element
const count = arr.filter(value => value === element).length;
// Step 2: Display the result
console.log(`${element} appears ${count} times`);
}
// Example usage
const numbers = [1, 2, 2, 3, 4, 4, 5];
countOccurrences(numbers, 2); // Output: 2 appears 2 times
Method 2: Count Occurrences of Each Element Using reduce()
// JavaScript Program to Count Occurrences of All Elements in an Array
// Author: https://www.rameshfadatare.com/
function countAllOccurrences(arr) {
// Step 1: Use reduce to count occurrences of each element
const occurrences = arr.reduce((acc, value) => {
acc[value] = (acc[value] || 0) + 1;
return acc;
}, {});
// Step 2: Display the result
for (const [element, count] of Object.entries(occurrences)) {
console.log(`${element} -> ${count}`);
}
}
// Example usage
const fruits = ['apple', 'banana', 'apple', 'orange', 'banana'];
countAllOccurrences(fruits);
/* Output:
apple -> 2
banana -> 2
orange -> 1
*/
Method 3: Count Occurrences Using forEach()
// JavaScript Program to Count Occurrences of All Elements in an Array using forEach()
// Author: https://www.rameshfadatare.com/
function countOccurrencesForEach(arr) {
const countMap = {};
// Step 1: Use forEach to count occurrences of each element
arr.forEach(value => {
if (countMap[value]) {
countMap[value]++;
} else {
countMap[value] = 1;
}
});
// Step 2: Display the result
for (let key in countMap) {
console.log(`${key} -> ${countMap[key]}`);
}
}
// Example usage
const names = ['John', 'Alice', 'John', 'Bob', 'Alice'];
countOccurrencesForEach(names);
/* Output:
John -> 2
Alice -> 2
Bob -> 1
*/
Explanation
Method 1: Count Occurrences of a Specific Element Using filter()
- The
filter()method is used to filter out only those elements that match the target value (element). The length of the filtered array gives the count of occurrences.
Method 2: Count Occurrences of All Elements Using reduce()
- The
reduce()method iterates over the array, building an accumulator object that tracks how many times each element appears. The object is then used to display the counts.
Method 3: Count Occurrences Using forEach()
- The
forEach()method iterates through the array and manually increments a counter in a map (object) for each element. This is a more explicit method of counting occurrences.
Output Example
2 appears 2 times
apple -> 2
banana -> 2
orange -> 1
John -> 2
Alice -> 2
Bob -> 1
Conclusion
This JavaScript program demonstrates how to count the occurrences of a specific element or all elements in an array using filter(), reduce(), and forEach(). Each method provides a different approach to solving the problem efficiently, and understanding these techniques is valuable for manipulating arrays and counting elements in JavaScript.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment