Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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' ]
How It Works
The function works in two main steps:
Step 1: Count occurrences of each element using forEach to build a frequency map.
Step 2: Use reduce to find elements with the highest frequency. If a new maximum is found, reset the result array. If an element has the same maximum frequency, add it to the result.
Alternative Approach Using Map
const getMostCommonWithMap = arr => {
const countMap = new Map();
// Count frequencies
arr.forEach(item => {
countMap.set(item, (countMap.get(item) || 0) + 1);
});
// Find maximum frequency
const maxCount = Math.max(...countMap.values());
// Get all items with maximum frequency
return [...countMap.entries()]
.filter(([item, count]) => count === maxCount)
.map(([item, count]) => item);
}
const testArr = ["x", "y", "x", "z", "y", "x"];
console.log(getMostCommonWithMap(testArr));
[ 'x' ]
Conclusion
Both approaches effectively find the most common elements in an array. The Map approach is more readable, while the reduce method is more compact and functional in style.
