Gil
Gil

Reputation: 137

Sorting Substring Array by Their Frequencies - JS

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?

Upvotes: 0

Views: 100

Answers (2)

Ling Zhong
Ling Zhong

Reputation: 1804

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;
});

Upvotes: 1

Natural Lam
Natural Lam

Reputation: 742

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];
});

Upvotes: 0

Related Questions