- 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
Finding the second most frequent character in JavaScript
We are required to write a JavaScript function that takes in a string and returns the character which makes second most appearances in the string.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const str = 'Hello world, I have never seen such a beautiful weather in the world'; const secondFrequent = str => { const map = {}; for(let i = 0; i < str.length; i++){ map[str[i]] = (map[str[i]] || 0) + 1; }; const freqArr = Object.keys(map).map(el => [el, map[el]]); freqArr.sort((a, b) => b[1] - a[1]); return freqArr[1][0]; }; console.log(secondFrequent(str));
Output
The output in the console will be −
e
Advertisements