word frequency in javascript

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

\"enter

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

6条回答
  •  無奈伤痛
    2020-12-05 17:26

    While both of the answers here are correct maybe are better but none of them address OP's question (what is wrong with the his code).

    The problem with OP's code is here:

    if(f==0){
        count[i]=1;
        uniqueWords[i]=words[i];
    }
    

    On every new word (unique word) the code adds it to uniqueWords at index at which the word was in words. Hence there are gaps in uniqueWords array. This is the reason for some undefined values.

    Try printing uniqueWords. It should give something like:

    ["this", "is", "anil", 4: "kum", 5: "the"]

    Note there no element for index 3.

    Also the printing of final count should be after processing all the words in the words array.

    Here's corrected version:

    function search()
    {
        var data=document.getElementById('txt').value;
        var temp=data;
        var words=new Array();
        words=temp.split(" ");
        var uniqueWords=new Array();
        var count=new Array();
    
    
        for (var i = 0; i < words.length; i++) {
            //var count=0;
            var f=0;
            for(j=0;j

    I have just moved the printing of count out of the processing loop into a new loop and added a if not undefined check.

    Fiddle: https://jsfiddle.net/cdLgaq3a/

提交回复
热议问题