JavaScript: Count the Occurrences of an Element in an Array

1. Introduction

Counting the number of occurrences of an element within an array is a common operation in data processing. In this tutorial, we'll dive deep into how you can count the occurrences of a specific element within a JavaScript array.

2. Program Overview

For this tutorial, our steps will involve:

1. Initialize an array with multiple elements.

2. Define a function to count the occurrences of an element in the given array.

3. Use the function and display the number of occurrences.

3. Code Program

let numbers = [2, 3, 2, 4, 3, 5, 2];  // An array with some repeated numbers

// Function to count the occurrences of a specific element in an array
function countOccurrences(arr, val) {
    let count = 0;  // Initialize count
    for(let i = 0; i < arr.length; i++) {
        if(arr[i] === val) {
            count++;  // Increment count if the current element matches the specified value
        }
    }
    return count;  // Return the final count
}

let valueToCheck = 2;
let occurrences = countOccurrences(numbers, valueToCheck);  // Count occurrences of the value 2 in the numbers array

console.log(In the array ${numbers}, the number ${valueToCheck} appears ${occurrences} times.);

Output:

In the array [2, 3, 2, 4, 3, 5, 2], the number 2 appears 3 times.

4. Step By Step Explanation

1. Array Initialization: We start by initializing an array numbers, which contains a mix of numbers, some of which are repeated.

2. Defining the countOccurrences Function: This function takes in an array (arr) and a value (val) as its parameters. We initialize a count variable to zero. As we loop through the array, every time we find a match with the specified value, we increment the count. Finally, the function returns the count.

3. Invoking the Function & Displaying the Result: We specify the number we want to check (in this case, 2), and call the countOccurrences function. Using console.log, we then display the array, the specified value, and its frequency.

Comments