• Tutorials
  • DSA
  • Data Science
  • Web Tech
  • Courses
October 20, 2022 |620 Views

Javascript program to count frequencies of array elements

  Share   Like
Description
Discussion

In this video, we will write Javascript Program to Count the Frequency of each element in an Array.

Examples:
Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}
Output : 
10 = 3
20 = 4
5 = 1

To count the frequency of each element in an array we use 2 approaches:

1. Using nested for loop: In the first approach, we run two for loops, and for every element count number of times, it occurs. To avoid duplicate printing, keep track of processed items.

2. Using MAP(),MAP.set(),MAP.has(): Here we use map(), traverse array elements, and count frequencies. To print elements according to the first occurrence, traverse the array one more time print frequencies of elements, and mark frequencies as -1 so that the same element is not printed multiple times.

Here we see the time complexity of both mentioned approaches:
1. Using nested for loop [Time complexity: O(n^2)]
2. Using MAP(),MAP.set(),MAP.has() [Time complexity : O(n)]

Javascript Program to Count the Frequency of each element in an Array : https://www.geeksforgeeks.org/javascript-program-for-counting-frequencies-of-array-elements/