Skip to content

Instantly share code, notes, and snippets.

@scolton99
Created May 25, 2021 23:23
Show Gist options
  • Select an option

  • Save scolton99/c7fde0a9d4acb3eaec6875cb556c2a5b to your computer and use it in GitHub Desktop.

Select an option

Save scolton99/c7fde0a9d4acb3eaec6875cb556c2a5b to your computer and use it in GitHub Desktop.
My solution to the word frequency problem in JavaScript.
const input = ["apple", "apple", "orange"];
const itemFreq = {};
for (const s of input) {
if (!(s in itemFreq))
itemFreq[s] = 0;
itemFreq[s]++;
}
const filtered = input.sort((x, y) => { itemFreq[x] < itemFreq[y] ? 1 : itemFreq[x] > itemFreq[y] ? -1 : 0 })
.filter((x, i) => input.indexOf(x) === i);
for (const s of filtered)
console.log(`${s}: ${itemFreq[s]}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment