JavaScript Program for Counting Frequencies of Array Elements

Counting frequencies of array elements means determining how many times each element appears in an array. This is a common programming task useful for data analysis, statistics, and various algorithms. JavaScript provides multiple approaches to solve this problem efficiently.

In this article, we'll explore five different methods to count element frequencies in JavaScript. Each approach has its own advantages - some prioritize simplicity, others performance, and some leverage built-in methods or external libraries.

Approaches to Count Array Elements Frequencies

Here are the five approaches we'll cover, each with detailed explanations and complete working examples:

Using Array Sorting

This approach first sorts the array, then counts consecutive identical elements. Sorting groups similar elements together, making frequency counting straightforward.

How It Works

  • Sort the array using the sort() method to group identical elements
  • Iterate through the sorted array, comparing each element with the previous one
  • Count consecutive identical elements and display frequencies
  • Handle the last element separately since the loop doesn't process it

Example

var arr = [7, 5, 5, 6, 6, 6, 7];
console.log("Original array:", arr);

arr.sort();
console.log("Sorted array:", arr);

var count = 1;
for(var i = 1; i 

Original array: [ 7, 5, 5, 6, 6, 6, 7 ]
Sorted array: [ 5, 5, 6, 6, 6, 7, 7 ]
The frequency of 5 is: 2
The frequency of 6 is: 3
The frequency of 7 is: 2

Using Maps

JavaScript Maps provide an efficient way to store key-value pairs. This approach uses a Map to store each element as a key and its frequency as the value.

How It Works

  • Create a new Map to store element-frequency pairs
  • Iterate through the array once
  • For each element, check if it exists in the map
  • If it exists, increment its count; otherwise, set count to 1

Example

var arr = [7, 5, 5, 6, 6, 6, 7];
var map = new Map();

for(var i = 0; i 

Element frequencies:
7: 2
5: 2
6: 3

Using an Object

Plain JavaScript objects can serve as hash tables for counting frequencies. This approach is simple and doesn't require additional data structures.

Example

let arr = [7, 5, 5, 6, 6, 6, 7];

function freq(arr) {
    let count = {};
    arr.forEach(item => {
        if(!count[item]) {
            count[item] = 0;
        }
        count[item]++;
    });
    return count;
}

let result = freq(arr);
console.log("Frequency count:", result);
Frequency count: { '5': 2, '6': 3, '7': 2 }

Using reduce() Method

The reduce() method provides a functional programming approach to count frequencies. It processes the array and builds the frequency object in a single pass.

Example

let arr = [7, 5, 5, 6, 6, 6, 7];

function freq(arr) {
    return arr.reduce((count, item) => {
        if(!count[item]) {
            count[item] = 0;
        }
        count[item]++;
        return count;
    }, {});
}

let result = freq(arr);
console.log("Frequency count using reduce:", result);
Frequency count using reduce: { '5': 2, '6': 3, '7': 2 }

Using Lodash Library

Lodash provides the _.countBy() method for counting frequencies. This external library approach offers a concise solution but requires including the library.

Example

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Counting Array Elements Frequencies</title>
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
</head>
<body>
    <h2>Counting Array Elements Frequencies</h2>
    <p>Using <strong>lodash _.countBy()</strong> method for counting frequencies.</p>
    <div id="result"></div>
    
    <script>
        let arr = [7, 5, 5, 6, 6, 6, 7];
        let count = _.countBy(arr);
        document.getElementById("result").innerHTML = JSON.stringify(count);
    </script>
</body>
</html>

Performance Comparison

Method Time Complexity Space Complexity Best For
Array Sorting O(n log n) O(1) Memory-constrained environments
Maps O(n) O(k) Large datasets with many unique elements
Object O(n) O(k) Simple, readable code
reduce() O(n) O(k) Functional programming style
Lodash O(n) O(k) Projects already using Lodash

k = number of unique elements in the array

Conclusion

Each approach offers different trade-offs between performance, readability, and memory usage. For most applications, the object-based approach provides the best balance of simplicity and efficiency. Choose the method that best fits your specific requirements and coding style preferences.

Updated on: 2026-03-15T23:19:01+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements