JSFiddle - React, Tailwind, and code Playground
by Tim Ko
JavaScript
// Return the n most frequent words from doc
function wordFrequency(doc, n) {
var wordsToOccurrences = {};
var occurrencesToWords = {};
var results = [];
var keys, count, remaining = n;
// Get all of the words from the document.
// Elements might include symbols, which are not included in words
// other than apostrophe, so remove them.
var words = doc.replace(/[\.,-\/#!?$%@\^&\*;:{}=\-_`~()<>]/g,"").toLowerCase().split(" ");
// Populate wordsToOccurrences object
// (key: word, value: number of occurrences)
for (var i = 0, ln = words.length; i < ln; i++) {
if (wordsToOccurrences.hasOwnProperty(words[i])) {
wordsToOccurrences[words[i]]++;
} else {
wordsToOccurrences[words[i]] = 1;
}
}
// Reverse the map from wordsToOccurrences to occurrencesToWords
// (key: number of occurrences, value: list of words with that number of occurrences)
keys = Object.keys(wordsToOccurrences);
for (var i = 0, ln = keys.length; i < ln; i++) {
var count = wordsToOccurrences[keys[i]];
if (occurrencesToWords.hasOwnProperty(count)) {
occurrencesToWords[count].push(keys[i]);
} else {
occurrencesToWords[count] = [keys[i]];
}
}
// Push the n most frequently occurring words into results array
keys = Object.keys(occurrencesToWords);
for (var i = keys.length - 1; i >= 0; i--) {
while (remaining > 0 && occurrencesToWords[keys[i]].length > 0) {
results.push(occurrencesToWords[keys[i]].pop());
remaining--;
}
if (remaining == 0) {
break;
}
}
return results;
}
console.log(wordFrequency("How is dog Chris, Chris!@#%$ Chris dog?",5));