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
Selected Reading
Find Second most frequent character in array - JavaScript
We are required to write a JavaScript function that takes in an array and returns the element that appears for the second most number of times.
Let's say the following is our array:
const arr = [1, 34, 4, 3, 2, 1, 4, 6, 4, 6, 5, 3, 6, 6];
The most frequent element is 6 (appears 4 times), but we want the second most frequent element, which is 4 (appears 3 times).
Example
const arr = [1, 34, 4, 3, 2, 1, 4, 6, 4, 6, 5, 3, 6, 6];
const secondMostFrequent = arr => {
const map = arr.reduce((acc, val) => {
if(acc.has(val)){
acc.set(val, acc.get(val) + 1);
} else {
acc.set(val, 1);
}
return acc;
}, new Map());
const frequencyArray = Array.from(map);
return frequencyArray.sort((a, b) => {
return b[1] - a[1];
})[1][0];
};
console.log(secondMostFrequent(arr));
Output
4
How It Works
The function works in three steps:
-
Count frequencies: Uses
reduce()with aMapto count how many times each element appears - Convert to array: Transforms the Map into an array of [element, frequency] pairs
- Sort and select: Sorts by frequency in descending order and returns the second element (index 1)
Alternative Approach Using Object
const arr = [1, 34, 4, 3, 2, 1, 4, 6, 4, 6, 5, 3, 6, 6];
const secondMostFrequentAlt = arr => {
const frequency = {};
// Count frequencies
arr.forEach(element => {
frequency[element] = (frequency[element] || 0) + 1;
});
// Sort by frequency
const sorted = Object.entries(frequency).sort((a, b) => b[1] - a[1]);
// Return second most frequent (convert back to number)
return Number(sorted[1][0]);
};
console.log(secondMostFrequentAlt(arr));
Output
4
Key Points
- The function assumes there are at least two distinct elements with different frequencies
- If multiple elements tie for second place, it returns one of them
- Both Map and Object approaches work effectively for frequency counting
- The sorting step arranges elements by frequency in descending order
Conclusion
Finding the second most frequent element involves counting frequencies, sorting by count, and selecting the second-highest. Both Map and Object approaches provide clean solutions for this common programming problem.
Advertisements
