Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 frequencyMap and from that map we will return the index that makes most appearances.
The code for doing so will be −
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 = {};
arr.forEach(el => {
if(frequencyMap[el]){
frequencyMap[el]++;
}else{
frequencyMap[el] = 1;
};
});
let highest, frequency = 0;
Object.keys(frequencyMap).forEach(key => {
if(frequencyMap[key] > frequency){
highest = parseInt(key, 10);
frequency = frequencyMap[key];
};
});
return arr.indexOf(highest);
};
console.log(mostAppearances(arr1));
console.log(mostAppearances(arr2));
Output
The output in the console will be −
6 1
Advertisements