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:

JavaScript
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.

Similar Reads

Methods to Find the most frequent element in an array in JavaScript

Table of Content Naive method using Loops and Sort functionUsing JavaScript ObjectUsing JavaScript Map and forEach methodUsing filter() and reduce()Using reduce() and a Frequency Map...

Naive method using Loops and Sort function

In this method, we will sort the given array and traverse it to find the maximum occurred element....

Using JavaScript Object

In this approach we will use JavaScript object to store the number and their occurences and find the element occurred most frequently....

Using JavaScript Map and forEach method

In this method, we will use JavaScript Map to map the values with number of occurrences and print the maximum occurred element...

Using filter() and reduce()

Using filter() to get unique elements, then reduce() to find the most frequent one by comparing filtered counts. This method efficiently determines the most frequent element in an array....

Using reduce() and a Frequency Map

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....

Contact Us