- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
How to get the most common values in array: JavaScript ?
We are required to write a JavaScript function that takes in an array of literals that have repeating values. Our function should return an array of the most common element(s) in the array (if two or more elements appear for the same number of most times then the array should contain all those elements).
Example
The code for this will be −
const arr1 = ["a", "c", "a", "b", "d", "e", "f"]; const arr2 = ["a", "c", "a", "c", "d", "e", "f"]; const getMostCommon = arr => { const count = {}; let res = []; arr.forEach(el => { count[el] = (count[el] || 0) + 1; }); res = Object.keys(count).reduce((acc, val, ind) => { if (!ind || count[val] > count[acc[0]]) { return [val]; }; if (count[val] === count[acc[0]]) { acc.push(val); }; return acc; }, []); return res; } console.log(getMostCommon(arr1)); console.log(getMostCommon(arr2));
Output
And the output in the console will be −
[ 'a' ] [ 'a', 'c' ]
Advertisements