How to use the Map() In Javascript
By using the “Map” Data Structure we can store the occurrence of elements in an array.
Example:This example shows the use of the above-explained approach.
function mostFrequentUsingMap(arr) {
const counts = new Map();
for (let num of arr) {
counts.set(num, (counts.get(num) || 0) + 1);
}
let mostFrequent;
let maxCount = 0;
counts.forEach((count, num) => {
if (count > maxCount) {
maxCount = count;
mostFrequent = num;
}
});
return mostFrequent;
}
const array = [1, 2, 2, 3, 2, 3, 4];
console.log(mostFrequentUsingMap(array));
Output
2
JavaScript Program to Find the Most Frequently Occurring Element in an Array
In this article, we are going to learn how to find the most frequently occurring element in an array we can use objects to count the occurrences of each element in an array.
Methods to find the most frequently occurring element in an array in JavaScript:
Table of Content
- Method 1: Using the reduce() method
- Method 2: Using the JavaScript Map()
- Method 3: Using the Math.max method
- Method 4: Using sorting
Contact Us