

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- Return the element that appears for second most number of times in the array JavaScript
- Counting how many times an item appears in a multidimensional array in JavaScript
- Take an array and find the one element that appears an odd number of times in JavaScript
- How to find the one integer that appears an odd number of times in a JavaScript array?
- Finding number that appears for odd times - JavaScript
- First element that appears even number of times in an array in C++
- Find the only element that appears b times using C++
- Find the element that appears once in sorted array - JavaScript
- Get the first and last item in an array using JavaScript?
- Find the element that appears once in an array where every other element appears twice in C++
- How to get the most common values in array: JavaScript ?
- Number of times a string appears in another JavaScript
- Get greatest repetitive item in array JavaScript
- Find the most frequent number in the array and how many times it is repeated in JavaScript
- Get the index of the nth item of a type in a JavaScript array
Advertisements