- 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
Find Second most frequent character in array - JavaScript
We are required to write a JavaScript function that takes in a string and returns the character from the string 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];
So, the frequent character appearing is −
6
But we want the output to be the second most frequent character i.e.
4
Let’s write the code for this function −
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
Following is the output in the console −
4
Advertisements