JavaScript Program to Count the Occurrences of an Element in an Array

🎓 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 of 2

  • Output: 2 appears 2 times

  • Input: ['apple', 'banana', 'apple', 'orange']

  • Output:

    • 'apple' -> 2
    • 'banana' -> 1
    • 'orange' -> 1

Solution Steps

  1. Initialize the Array: Provide an array with some duplicate elements.
  2. Count Occurrences of a Specific Element: Use the filter() method to count occurrences of a single element.
  3. Count Occurrences of All Elements: Use reduce() to count the occurrences of each unique element.
  4. 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:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare