0

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.

Community
  • 1
  • 1
theamateurdataanalyst
  • 2,794
  • 4
  • 38
  • 72

1 Answers1

0

Check this out, since you can't sort an object we turn the object into an array.

function charOccour(str) {
    //returns object detailing characters and its count found in str
    //case sensitive
    var found = {}; //key is char found, and value is count of occourances in str
    for (var i=0; i<str.length; i++) {
        console.log('on char = ', str[i]);
        if(str[i] in found) {
            unique = false;
            found[str[i]]++;
        } else {
            found[str[i]] = 1;
        }
    }
    return found;
}

var ret = charOccour('blah blah'); //Object { b: 2, l: 2, a: 2, h: 2,  : 1 }
//turn ret to array and sort it

var arr = [];
for (var letter in ret) {
  arr.push([letter, ret[letter]])
};
console.log(arr.toString());

arr.sort(function(a, b) {
  return a[1] < b[1];
});
//['b',2], ['l',2], ['a',2], ['h',2], [' ',1]
Noitidart
  • 35,443
  • 37
  • 154
  • 323