Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.