- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Second most frequent character in a string - JavaScript
We are required to write a JavaScript function that takes in a string and returns the character from the string that appears for second most number of times.
Let’s say the following is our string −
const str = 'This string will be used to calculate frequency';
Above, the second most frequent character is “e”.
Example
Let us now see the complete code −
const str = 'This string will be used to calculate frequency'; const secondMostFrequent = str => { const strArr = str.split(''); const map = strArr.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(str));
Output
This will produce the following output in console −
e
- Related Articles
- Find Second most frequent character in array - JavaScript
- Finding the second most frequent character in JavaScript
- Returning the second most frequent character from a string (including spaces) - JavaScript
- Program to find second most frequent character in C++
- Python program to find Most Frequent Character in a String
- Find the second most frequent element in array JavaScript
- Python program to find Least Frequent Character in a String
- Finding n most frequent words from a sentence in JavaScript
- Finding the most frequent word(s) in an array using JavaScript
- Most Frequent Subtree Sum in C++
- Find most frequent element in a list in Python
- Most Frequent Number in Intervals in C++
- How to find Second most repeated string in a sequence in android?
- Most frequent element in an array in C++
- Finding second smallest word in a string - JavaScript

Advertisements