JavaScript Program for Counting Frequencies of Array Elements



Counting frequencies of array elements means we have to count the number of times an element from the array appears in the given array. We will be discussing five different approaches to achieve this. We can use some inbuilt data structures or external libraries for easy implementation.

In this article we are having an array with duplicate elements, our task is to count frequencies of array elements in JavaScript. Users must be familiar with array and it's functions, JavaScript methods and function, loops, conditional statement and Javascript objects.

Approaches to Count Array Elements Frequencies

Here is a list of approaches for counting frequencies of array elements in Javascript which we will be discussing in this article with stepwise explaination and complete example codes.

Using Array sorting

To count frequencies of array elements in Javascript, we will sort the array using sort() method and check previous and current element if they are same.

  • First, we have declared an array arr and then sorted the array using the inbuilt sort() method.
  • We will create an array that will store the elements and their respective frequencies in the given array.
  • We will create a variable count to store the number of times the current element occurs.
  • We will iterate over the array and at each iteration using for loop, we will check if the current element is equal to the previous element or not using if/else statement.
  • If the current element is equal to the previous one, then we will increase the value of the count.
  • If the current element is not equal to the previous element, then we will store the count with the previous element as a key-pair in the array indicating the frequency of the current element.
  • Also, we will update the value of the count to 1. After iterating over the array we will store the frequency of the last element of the sorted array as it will not be stored and loop ended.
  • The output is displayed in web console using console.log().

Example

Here is a complete example code implementing above mentioned steps for counting frequencies of array elements in Javascript using array sorting.

var arr = [7, 5, 5, 6, 6, 6, 7];
arr.sort();
var count = 1;
for(var i = 1; i 


Using Maps

In this approach for counting frequencies of array elements in Javascript, we have used map data structure.

  • First, we have declared an array arr and then we will create the map using the new keyword.
  • We will iterate over the array and for each element, we will check if the current element is present in the map then we will increase the value stored for the current element which is frequency.
  • If the element is not stored then we will add it to the map as a key and will give a value of 1.
  • After iterating over the array we can print the values stored in the map as key-value pairs in web console using console.log().

Example

Here is a complete example code implementing above mentioned steps for counting frequencies of array elements in Javascript using maps.

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


Using an Object

In this approach for counting frequencies of array elements in Javascript, we have used an object and conditional statement.

  • We have declared an array arr and created a function freq() which accepts the array arr as argument.
  • Then we have created an empty object count which will store the key value pair of element and their occurence.
  • Then we have used forEach to iterate over elements of the array. We have used if/else statement to check the occurence of element in the array.
  • If element has not appeared before in the array then, it will set the count[item] to 0 and increase the count. If the element has appeared before in the array then it simply increment the count by 1.
  • After completion of loop, count is returned and displayed in the web console using console.log().

Example

Here is a complete example code implementing above mentioned steps for counting frequencies of array elements in Javascript using an object.

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;
}
console.log(freq(arr));

Using reduce() Method

In this approach for counting frequencies of array elements in Javascript, we have used reduce() method which creates and maintains object and iterate over the elements of the array.

  • We have declared an array arr and created a function freq() which accepts the array arr as argument.
  • Here reduce() method is used to iterate over elements of the array and return an object count.
  • We have used if/else statement to check the occurence of element in the array.
  • If element has not appeared before in the array then, it will set the count[item] to 0 and increase the count. If the element has appeared before in the array then it simply increment the count by 1.
  • After completion of loop, count is returned and displayed in the web console using console.log().

Example

Here is a complete example code implementing above mentioned steps for counting frequencies of array elements in Javascript using reduce() method.

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;
    }, {});
}
console.log(freq(arr));

Using Lodash Library

In this approach, we have used _.countBy() method of Lodash library for counting frequencies of array elements in Javascript.

  • We have included the CDN link of Lodash Library using script tag in head section of the document
  • We have used a div tag to display the output in HTML document using getElementById() method and innerHTML property.
  • Then we have declared an array arr and used _.countBy() method of Lodash library to count the occurence of elements in the array and stored it in count and converted the object to string using JSON.stringify() method to display in HTML document.

Example

Here is a complete example code implementing above mentioned steps for counting frequencies of array elements in Javascript using Lodash library.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        Counting Array Elements Frequencies
    </title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
</head>
<body>
    <h2>
        Counting Array Elements Frequencies
    </h2>
    <p>
        In this example, we have used <strong>lodash _.countBy()
        </strong> method for counting array elements frequencies
        in Javascript.
    </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>

Conclusion

In this article, to find closest number in array using Javascript we have understood three different approaches which are: by array sorting, Maps data structure, using object, reduce() method and Lodash library ._countBy() method.

Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Updated on: 2024-12-05T17:46:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements