How to use reduce() and a Frequency Map In Javascript
In this approach, we use the reduce() function to build a frequency map of the elements in the array. Then, we find the element with the highest frequency by iterating through this map.
Example:
const arr = [
1, 1, 3, 5, 7, 6, 8, 5, 6, 4,
7, 6, 0, 2, 1, 6, 8, 9, 5,
];
// Create a frequency map using reduce
const frequencyMap = arr.reduce((acc, curr) => {
acc[curr] = (acc[curr] || 0) + 1;
return acc;
}, {});
// Find the most frequent element
let maxCount = 0;
let mostFrequentElement;
for (const [element, count] of Object.entries(frequencyMap)) {
if (count > maxCount) {
maxCount = count;
mostFrequentElement = element;
}
}
console.log("The most occurred element is: " + mostFrequentElement);
Output
The most occurred element is: 6
Most Frequent Element in an Array using JavaScript
We will demonstrate different methods to find the most frequent element in an array in JavaScript. We will be given an array with multiple occurrences of values in that array and we have to output the maximum occurred element in that array.
Contact Us