2011-07-03 89 views

回答

18

您應該通過的話字符串分割成詞,然後循環並且將每一個計數器:

var wordCounts = { }; 
var words = str.split(/\b/); 

for(var i = 0; i < words.length; i++) 
    wordCounts["_" + words[i]] = (wordCounts["_" + words[i]] || 0) + 1; 

"_" +允許它來處理像constructor詞已經是對象的屬性。

您可能希望寫入words[i].toLowerCase()以便不區分大小寫。

+1

只是出於好奇 - 你有這個片段鋪設在某處,或者你想出解決方案只是爲了這個答案?無論哪種方式,這真棒。 :) –

+0

@ajax:我當場創建它。謝謝! – SLaks

+0

嘿,非常感謝,我只是想知道,你能解釋一下/ \ b /參數嗎?這是一個正則表達式是嗎? –

0

從未來開始,再次詢問這個問題,但是我對解決方案提前開始並將其標記爲已回答。無論如何,這是SLak答案的補充。

function nthMostCommon(string, ammount) { 
    var wordsArray = string.split(/\s/); 
    var wordOccurrences = {} 
    for (var i = 0; i < wordsArray.length; i++) { 
     wordOccurrences['_'+wordsArray[i]] = (wordOccurrences['_'+wordsArray[i]] || 0) + 1; 
    } 
    var result = Object.keys(wordOccurrences).reduce(function(acc, currentKey) { 
     /* you may want to include a binary search here */ 
     for (var i = 0; i < ammount; i++) { 
      if (!acc[i]) { 
       acc[i] = { word: currentKey.slice(1, currentKey.length), occurences: wordOccurrences[currentKey] }; 
       break; 
      } else if (acc[i].occurences < wordOccurrences[currentKey]) { 
       acc.splice(i, 0, { word: currentKey.slice(1, currentKey.length), occurences: wordOccurrences[currentKey] }); 
       if (acc.length > ammount) 
        acc.pop(); 
       break; 
      } 
     } 
     return acc; 
    }, []); 
    return result; 
} 
相關問題