2011-07-03 8 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

이 질문이 다시 제기 된 미래에서 왔지만 해결책이 너무 일찍 시작되어 답변으로 표시되었습니다. 어쨌든, 그것은 SLaks의 답을 보완합니다.

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; 
} 
관련 문제