字频率计数器

时间:2016-02-18 06:15:20

标签: javascript counter frequency word

来自以下代码

var words = 'one two three four one two three';
wordArray = words.split(' ');
var newArray = [];
var words = {};

$.each(wordArray, function (ix, word ) {
    if ($.inArray(word , newArray) > -1) {
        words[word]++;
    }
    else {
        console.log('that wasnt in the array');
        words[word] = 1;
    }

});

如何获得按字数排序的字频率的降序输出?感谢

2 个答案:

答案 0 :(得分:1)

var wordsString = 'one two three four one two three';
var wordArray = words.split(' ');
var wordCounter = {};


for(var i=0; i<wordArray.length; i++){
    if(wordCounter[wordArray[i]]){
        wordCounter[wordArray[i]] += 1;
    }else{
        wordCounter[wordArray[i]] = 1;
    }
}

此时我们有每个&#34; word&#34;的总数,但没有排序。 要添加排序,我们只需使用Array.sort()函数

对wordArray进行排序
var wordArraySortFunction = function(word1, word2){
    if(wordCounter[word1] < wordCounter[word2]){
        return -1;
    }else if(wordCounter[word1] == wordCounter[word2]){
        return 0;
    }else if(wordCounter[word1] > wordCounter[word2]){
        return 1;
    }
}

wordArray.sort(wordArraySortFunction);

如果要反转排序顺序,可以重写排序功能:

var wordArraySortFunction = function(word1, word2){
    if(wordCounter[word1] < wordCounter[word2]){
        return 1;
    }else if(wordCounter[word1] == wordCounter[word2]){
        return 0;
    }else if(wordCounter[word1] > wordCounter[word2]){
        return -1;
    }
}

或者你可以在排序数组上使用Array.reverse()

wordArray.reverse();

现在我们根据频率对单词进行排序,我们可以输出它们:

for(var i=0; i<wordArray.length; i++){
    console.log(wordArray[i] + ': ' + wordCounter[wordArray[i]]);   
}

答案 1 :(得分:0)

var wordsString = 'one two three four one two three';
var wordArray = words.split(' ');
var words = {};

$.each(wordArray, function (i, word ) {
    if (word in words) {
        words[word] += 1 ;
    }
    else {
        console.log('that wasnt in the array');
        words[word] = 1;
    }

});