我使用以下代码生成带有给定字符串和子字符串长度的子字符串数组:
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;
};
我想做的下一件事是按频率对子串进行排序。
我该怎么做?
答案 0 :(得分:1)
继续你的代码。请参阅注释中的解释:
// 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;
});
答案 1 :(得分:0)
你需要有一个子串的数组,然后你可以为JS sort
方法提供比较器来进行排序。
假设您有一个子串数组,即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];
});