How to use the Math.max method In Javascript
By using “Math.max” also we can find the highest frequency of given array elements.
Example: This example shows the use of the above-explained approach.
function mostFrequentUsingMathMax(arr) {
const counts = {};
for (let num of arr) {
counts[num] = (counts[num] || 0) + 1;
}
const maxCount =
Math.max(...Object.values(counts));
const mostFrequent =
Object.keys(counts).find(key =>
counts[key] === maxCount);
return mostFrequent;
}
const array = [1, 5, 2, 3, 5, 6, 4];
console.log(mostFrequentUsingMathMax(array));
Output
5
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