Skip to content

Instantly share code, notes, and snippets.

@deckerego
Created September 3, 2018 21:45
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 deckerego/f54d9f7e3dc2ae33493866950cdd4fa1 to your computer and use it in GitHub Desktop.
Save deckerego/f54d9f7e3dc2ae33493866950cdd4fa1 to your computer and use it in GitHub Desktop.
Count token frequency (word count) for a string in JavaScript
var testString = "cat you cat are a cat who is a cat nope not a cat";
var tokenized = testString.split(" ");
var tokenFreq = tokenized.reduce((acc, val) => { acc[val] ? acc[val]++ : acc[val] = 1; return acc; }, {});
Object.entries(tokenFreq).forEach(entry => console.log(entry[0], ": ", entry[1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment