DEV Community

Sorting Characters in a String By Their Frequency

Alisa Bajramovic on May 22, 2020

Today's algorithm is: given a string, sort it in decreasing order based on the frequency of characters. For example, if you were given the str...
Collapse
 
chety profile image
Chety

Hi Alisa,

Thanks for the series. I also solved it with same approach but used different techniques. I am sharing mine , hope it helps someone else.

var frequencySort = function(s) {
    const charCountHash = Array.from(s).reduce((acc,ch) => {
    acc[ch] = (acc[ch] || 0) + 1;
    return acc;
  }, {});

  return Object.entries(charCountHash).sort((a,b) => b[1] - a[1]).reduce((acc,charHash) => {
        const [ch,count] = charHash;
        return acc += ch.repeat(count);        
   }, ""); 
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
mr_abbos profile image
Abbos Shamsiddin

Thanks, Alisa I am learning more things by your algorithm solutions.