word frequency in javascript

后端 未结 6 1438
自闭症患者
自闭症患者 2020-12-05 16:57

\"enter

How can I implement javascript function to calculate frequency of each word in

6条回答
  •  长情又很酷
    2020-12-05 17:17

    Here is a JavaScript function to get the frequency of each word in a sentence:

    function wordFreq(string) {
        var words = string.replace(/[.]/g, '').split(/\s/);
        var freqMap = {};
        words.forEach(function(w) {
            if (!freqMap[w]) {
                freqMap[w] = 0;
            }
            freqMap[w] += 1;
        });
    
        return freqMap;
    }
    

    It will return a hash of word to word count. So for example, if we run it like so:

    console.log(wordFreq("I am the big the big bull."));
    > Object {I: 1, am: 1, the: 2, big: 2, bull: 1}
    

    You can iterate over the words with Object.keys(result).sort().forEach(result) {...}. So we could hook that up like so:

    var freq = wordFreq("I am the big the big bull.");
    Object.keys(freq).sort().forEach(function(word) {
        console.log("count of " + word + " is " + freq[word]);
    });
    

    Which would output:

    count of I is 1
    count of am is 1
    count of big is 2
    count of bull is 1
    count of the is 2
    

    JSFiddle: http://jsfiddle.net/ah6wsbs6/

    And here is wordFreq function in ES6:

    function wordFreq(string) {
      return string.replace(/[.]/g, '')
        .split(/\s/)
        .reduce((map, word) =>
          Object.assign(map, {
            [word]: (map[word])
              ? map[word] + 1
              : 1,
          }),
          {}
        );
    }
    

    JSFiddle: http://jsfiddle.net/r1Lo79us/

提交回复
热议问题