

- 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
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' ]
- Related Questions & Answers
- Comparing objects in JavaScript and return array of common keys having common values
- Get the item that appears the most times in an array JavaScript
- How to get the first n values of an array in JavaScript?
- How to get all unique values in a JavaScript array?
- What are the most common teenage problems?
- What are the most common mental illnesses?
- Get the count of the most frequently occurring values in MySQL?
- The most Common POSIX System Calls in Python
- Python - Most common Combination in Matrix
- Get the max n values from an array in JavaScript
- How to get the numbers which can divide all values in an array - JavaScript
- How to filter out common array in array of arrays in JavaScript
- How to get the most out of Canva?
- Which is the most common lost article in India?
- How to get the values of an object in JavaScript?
Advertisements