Skip to content

Instantly share code, notes, and snippets.

@jtribble
Created April 30, 2016 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtribble/44f5068662d8ffa98b29819a39898df9 to your computer and use it in GitHub Desktop.
Save jtribble/44f5068662d8ffa98b29819a39898df9 to your computer and use it in GitHub Desktop.
Given a random array of words, find all duplicates of words and return the 1st "n" in order from most frequent to least frequent (words with identical frequency would be listed alphabetically)
// Given a random array of words, find all duplicates of words and return the
// 1st "n" in order from most frequent to least frequent (words with identical
// frequency would be listed alphabetically)
/**
* Find the most frequent words in an array of words
*
* @param {array} words - The list of words
* @param {number} n - The number of results to show
* @return {array} - An array of word+count objects, sorted
*/
var frequentWords = function(words, n) {
// convert the words array into a hash object
const hash = words.reduce((acc, curr) => {
acc[curr] = acc.hasOwnProperty(curr) ? acc[curr] + 1 : 1;
return acc;
}, {});
// transform the hash data stucture into an ordered array
const freqWords = [];
for (let prop in hash) {
if (hash.hasOwnProperty(prop)) {
// build the word data object
const wordData = {
count: hash[prop],
word: prop
};
// determine the proper position for the object
let i = 0;
while (freqWords[i] !== undefined && (
(freqWords[i].count > wordData.count) ||
(freqWords[i].count === wordData.count && freqWords[i].word.charAt(0) > wordData.word.charAt(0))
)) {
i++;
}
// insert the object at the proper position
freqWords.splice(i, 0, wordData);
}
}
// return the results array
return freqWords.slice(0, n);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment