0

I generate an array of substrings with a given string and a substring length using this code:

function NthFrequencyCount(string,length){

    var frequency = {};
    for(var i = 0;i < string.length-length;i++){
        var char = string.substring(i,i+length);

        if(char.indexOf(' ') === -1){
            if(frequency[char] === undefined)
                frequency[char] = 1;
            else
                frequency[char]++;
        }
    }
    return frequency;
};

The next thing that I would like to do is to sort the substrings by their frequencies.

How do I do that?

2
  • 2
    sounds like a good plan. You have not asked a question though? What is your question? Commented Nov 8, 2015 at 22:38
  • Are you having further issues moving on? If your problem is solved then you should mark the answer that helped resolving the problem as accepted. This helps other people who have the same question. Happy Coding :) Commented Nov 8, 2015 at 23:21

2 Answers 2

1

Continuing from your code. See explanations in comments:

// frequency object is populated
entries = [];
for (var key in frequency) { // convert freqeuncy into array of entries
  if (p.hasOwnProperty(key)) {
    entries.push({ key:key, freq:frequency[key] });
  }
}

entries.sort(function(a, b) { // sort entries by freq
    return a.freq - b.freq;
}).map(function(entry) { // pluck out only the key, which is the substring
    return entry.key;
});
Sign up to request clarification or add additional context in comments.

Comments

0

you need to have an array of the substring, and then you can provide the comparator to the the JS sort method to do the sorting.

Assume you have an array of the substrings, namely substrings:

var frequencies = nthFrequencyCount(string, length);
substrings.sort(function (a, b) {
    // This sort the substrings in ascending order of frequency
    return frequencies[a] - frequencies[b];
});

2 Comments

I don't have the "substrings" array,what I get from my "NthFrequencyCount" is an array that in which you use the substring to access the data,and the data is a number which represent the frequency.
your NthFrequencyCount returns an object, not an array, so you cannot sort it. If you can't create or access such array before hand, that @LingZong's solution above would help to create that array from your frequencies objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.