This post will discuss how to build a frequency map of a collection in JavaScript.

The frequency map is a data structure that stores the number of occurrences of each element in a collection, such as an array or a string. There are several ways to build a frequency map in JavaScript:

1. Using an object literal

If the collection is an array of numbers or strings, we can use an object literal to store the frequency map as key-value pairs, where the keys are the elements and the values are the counts. We can iterate over the collection with a for loop and increment the count of each element in the object. The following code illustrates this:

Download  Run Code

 
We can also iterate over the collection using a forEach() function, and increment the count for each element using the object bracket notation. We can shorten the code by using a logical OR operator (||) to provide a default value of zero if the current element is not already present in the object.

Download  Run Code

 
The above code creates an object with the elements as keys and their counts as values. However, this does not distinguish between different types of keys, such as 1 and "1".

2. Using a Map object

We can create a Map object to store any type of values as keys and their counts as values. We can iterate over the collection with a for…of loop and increment the count of each element in the Map. This works well for collections that contain complex objects, such as dates, maps, sets, etc. It also distinguishes between different types of keys, such as 1 and "1". The following code illustrates this:

Download  Run Code

 
We can shorten the code by iterating over the collection using a forEach() function, and use a logical OR operator (||) to avoid the extra call to the has() function.

Download  Run Code

3. Using Array.reduce() function

The Array.reduce() function applies a function to each element of the collection and accumulates the result in an accumulator. We can use a plain object or a Map as the accumulator and update its values based on the elements. The following code illustrates this:

Download  Run Code

4. Using a custom class

We can also create a custom class that extends the Map object and adds functions to add and delete elements from the frequency map. We can also adds functionality to sort and return the frequency map in different formats. This works well for collections that require more functionality and flexibility than the built-in Map object. The following code illustrates this:

Download  Run Code

That’s all about building a frequency map of a collection in JavaScript.