JavaScript - Most Frequent Element in an Array
Last Updated :
23 Jul, 2025
Let us talk about different methods to find the most frequent element in an array in JavaScript.
Using JavaScript Object (For Small to Moderate Arrays)
In this approach we use JavaScript object to store the number and their occurrences and find the element occurred most frequently.
JavaScript
function mostFrequent(arr) {
let m = {};
let maxCount = 0;
let res = null;
for (let x of arr) {
m[x] = (m[x] || 0) + 1;
if (m[x] > maxCount) {
maxCount = m[x];
res = x;
}
}
return res;
}
// Example usage
let arr = [1, 3, 1, 3, 2, 1];
console.log(mostFrequent(arr));
Using JavaScript Map (For Large Arrays and More Data Types Supported)
In this method, we use JavaScript Map to map the values with number of occurrences and print the maximum occurred element
JavaScript
function mostFrequent(arr) {
let m = new Map();
let maxCount = 0;
let res = null;
for (let num of arr) {
let count = (m.get(num) || 0) + 1;
m.set(num, count);
if (count > maxCount) {
maxCount = count;
res = num;
}
}
return res;
}
// Example usage
let arr = [1, 3, 1, 3, 2, 1];
console.log(mostFrequent(arr));
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.
JavaScript
const array = [1, 2, 3, 2, 2, 3, 1, 4, 2];
const mostFrequent = Array.from(new Set(array)).reduce((prev, curr) =>
array.filter(el => el === curr).length > array.filter(el => el === prev).length ? curr : prev
);
console.log(mostFrequent);
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.
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);
OutputThe most occurred element is: 6
Using Lodash _.countBy()
Using Lodash's _.countBy() function, you can count the occurrences of each element in an array. Then, use _.maxBy() to find the key with the highest count, identifying the most frequent element.
Example:
JavaScript
const _ = require('lodash');
function mostFrequent(arr) {
let freq = _.countBy(arr);
return _.maxBy(Object.keys(freq), o => freq[o]);
}
console.log(mostFrequent([1, 2, 2, 3, 3, 3]));
Output:
3
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics