Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Get the item that appears the most times in an array JavaScript
Let's say we are required to write a function that takes in an array of string/number literals and returns the index of the item that appears for the most number of times. We will iterate over the array and prepare a frequency map, and from that map we will return the index that makes the most appearances.
Example
const arr1 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34, 65, 34, 22, 67, 34];
const arr2 = [12, 5, 6, 76, 23, 12, 34, 5, 23, 34];
const mostAppearances = (arr) => {
const frequencyMap = {};
// Build frequency map
arr.forEach(el => {
if(frequencyMap[el]){
frequencyMap[el]++;
}else{
frequencyMap[el] = 1;
};
});
// Find element with highest frequency
let highest, frequency = 0;
Object.keys(frequencyMap).forEach(key => {
if(frequencyMap[key] > frequency){
highest = parseInt(key, 10);
frequency = frequencyMap[key];
};
});
// Return first index of most frequent element
return arr.indexOf(highest);
};
console.log(mostAppearances(arr1));
console.log(mostAppearances(arr2));
Output
6 1
How It Works
The function works in three steps:
- Build frequency map: Count occurrences of each element using an object
- Find highest frequency: Loop through the map to find the element with maximum count
-
Return index: Use
indexOf()to get the first occurrence of the most frequent element
Alternative Approach Using Map
const mostAppearancesMap = (arr) => {
const frequencyMap = new Map();
// Count frequencies
for(let item of arr) {
frequencyMap.set(item, (frequencyMap.get(item) || 0) + 1);
}
// Find most frequent element
let maxCount = 0;
let mostFrequent = null;
for(let [item, count] of frequencyMap) {
if(count > maxCount) {
maxCount = count;
mostFrequent = item;
}
}
return arr.indexOf(mostFrequent);
};
console.log(mostAppearancesMap([3, 1, 3, 3, 2, 1])); // Index of first 3
0
Conclusion
Both approaches use frequency counting to find the most common element. The Map version is cleaner and handles different data types better than objects.
Advertisements
