VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascrip-t-count-frequencies-in-an-array/

⇱ JavaScript- Count Frequencies in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript- Count Frequencies in an Array

Last Updated : 23 Jul, 2025

These are the following ways to count the frequency:

1. Using Object (Efficient for Small to Moderate Arrays)

We use JavaScript Objects to store frequencies, we iterate over the array using the forEach() method. For each element, we check if the element already exists as a key in the res object. If it does, we increment its count; if not, we initialize it to 1.

2. Using Map (Easiest and Efficient for All Types of Arrays)

Here, we use a Map to store the frequency of each element. We iterate over the array using forEach() and use the get() method to check if the element is already in the Map.


Output
{ '1': 1, '2': 3, '3': 3, '4': 3 }

3. Using reduce() with Map (Similar to 2nd)

This approach uses the reduce() method, which is typically used to accumulate results. We can also use reduce with Objects.


Output
{ '1': 1, '2': 3, '3': 3, '4': 3 }

4. Using for...of Loop Object (Similar to 2nd, only loop is different)

This approach uses the for...of loop to iterate through each element of the array and store frequencies in Map. We can also use this with Object.


Output
{ '1': 1, '2': 3, '3': 3, '4': 3 }
Comment
Article Tags: