How to use the Map In Javascript
- We start by creating an empty Map called frequency. We then iterate through each element of the input array using a for…of loop.
- For each element, we use the Map.set() method to either update its existing count in the Map or initialize it with a count of 1.
- The key in the Map represents the unique element from the array, and the value represents its frequency. After processing all elements, we return the Map object, which contains the frequencies of each unique element.
- If you want to convert the Map to a regular object (similar to the previous methods), you can use Object.fromEntries(frequencyMap) as shown in the example, which converts the Map key-value pairs into an object with properties representing the unique elements and values representing their frequencies.
Example:
function calculateElementCounts(inputArray) {
const counts = new Map();
for (const item of inputArray) {
counts.set(item, (counts.get(item) || 0) + 1);
}
return counts;
}
const inputData =
[5, 6, 6, 7, 7, 7, 8, 8, 8, 8];
const countsMap =
calculateElementCounts(inputData);
const countsObject =
Object.fromEntries(countsMap);
console.log(countsObject);
Output
{ '5': 1, '6': 2, '7': 3, '8': 4 }
JavaScript Program to Determine the Frequency of Elements in an Array and Represent it as an Object
In this article, we are going to learn how can we find the frequency of elements in an array and represent it as an object. The frequency of elements in an array in JavaScript refers to how many times each unique element appears in the array.
These are the following approaches by using these we can find the frequency of elements:
Table of Content
- Using a for-loop
- Using the reduce method
- Using the Map
- Using the forEach Method