Hi guys I want to create a function that takes in a string and returns an object that has a mapping of the letter frequencies in the string. In addition I want my function to return the object sorted by frequency in decreasing order. So what I am expecting is letterfreq("ssabbb")
=> {b:3,s:2,a:1}
. I have written a function that returns a mapping of frequencies and this function is
function letterfreq(str) {
var mapping = {};
var NoSpaceStr = str.replace(/[\s]/g,"");
for(var i = 0; i < NoSpaceStr.length; i++){
if(!mapping[NoSpaceStr[i]])
{mapping[NoSpaceStr[i]] = 0;}
mapping[NoSpaceStr[i]] += 1;}
return mapping
}
The problem is I am a little stumped about sorting based on property values. I checked out this and the first response has a high upvoted answer. He makes the object an array of arrays and then goes on to say "Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do." I am not exactly sure how to do this. I was wondering if anyone had a solution to this that a beginner could understand. The answers to the question in the link I posted are a little overwhelming. Any advice or help would be great. Thanks! By the way this is one part of a CoderByte problem.