Sorting string characters by frequency in JavaScript

JavascriptWeb DevelopmentFront End Technology


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.


The code for this will be −

 Live Demo

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;

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


And the output in the console will be −

Published on 18-Mar-2021 08:28:02