- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Highest occurrence in an array or first selected in JavaScript
We are required to write a JavaScript function that takes in an array of literal values. Our function should then return the highest occurrence of an array value, and if there's an equal occurrence, we should return the first selected value of the equal occurrences.
const arr = ['25', '50', 'a', 'a', 'b', 'c']
In this case, we should return 'a'
const arr = ['75', '100', 'a', 'b', 'b', 'a']
In this case, I should also get 'a'
Example
The code for this will be −
const arr = ['25', '50', 'a', 'a', 'b', 'c']; const arr1 = ['75', '100', 'a', 'b', 'b', 'a']; const getMostFrequentValue = (arr = []) => { let count = 0, ind = -1; arr.forEach((el, i) => { this[el] = this[el] || { count: 0, ind: i }; this[el].count++; if (this[el].count > count) { count = this[el].count; ind = this[el].ind; return; }; if (this[el].count === count && this[el].ind < ind) { ind = this[el].ind; }; }, Object.create(null)); return arr[ind]; }; console.log(getMostFrequentValue(arr)); console.log(getMostFrequentValue(arr1));
Output
And the output in the console will be −
a a
- Related Articles
- Highest and lowest in an array JavaScript
- Returning the highest value from an array in JavaScript
- Removing the odd occurrence of any number/element from an array in JavaScript
- Finding the first redundant element in an array - JavaScript
- Sort an integer array, keeping first in place in JavaScript
- How to get the first index of an occurrence of the specified value in a string in JavaScript?
- Sort an array to have specific items first in the array - JavaScript
- Find n highest values in an object JavaScript
- Return the first duplicate number from an array in JavaScript
- Finding the first non-consecutive number in an array in JavaScript
- Display first selected row in MySQL?
- First occurrence of True number in Python
- Replace all occurrence of specific words in a sentence based on an array of words in JavaScript
- Constructing an array of addition/subtractions relative to first array element in JavaScript
- Index of first occurrence in StringCollection in C#?

Advertisements