
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting String Characters by Frequency in JavaScript
Problem
We are required to write a JavaScript function that takes in the string of characters as the only argument.
Our function should prepare and a new string based on the original string in which the characters that appear for most number of times are placed first followed by number with decreasing frequencies.
For example, if the input to the function is −
const str = 'free';
Then the output should be −
const output = 'eefr';
Output Explanation:
Since e appears twice it is placed first followed by r and f.
Example
The code for this will be −
const str = 'free'; const frequencySort = (str = '') => { let map = {} for (const letter of str) { map[letter] = (map[letter] || 0) + 1; }; let res = ""; let sorted = Object.keys(map).sort((a, b) => map[b] - map[a]) for (let letter of sorted) { for (let count = 0; count < map[letter]; count++) { res += letter } } return res; }; console.log(frequencySort(str));
Code Explanation:
The steps we took are −
First, we prepared a hashmap of letter count
Then we sorted the map by count of letters
And finally, we generated res string from the sorted letter
Output
And the output in the console will be −
eefr
Advertisements