
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
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
Advertisements