Skip to content

Instantly share code, notes, and snippets.

@OrderAndCh4oS
Created September 26, 2024 00:27
Show Gist options
  • Select an option

  • Save OrderAndCh4oS/9810f744531c5851d8bdf5157cd2dae1 to your computer and use it in GitHub Desktop.

Select an option

Save OrderAndCh4oS/9810f744531c5851d8bdf5157cd2dae1 to your computer and use it in GitHub Desktop.
Count Occurrences
const str = 'onè, twö, three and, ö four. *%#@ four and three!!! 😍 💕, 👍👌\nblah blah blah hyphenated-word thing–endash and an—emdash a/slash some!!thing 10:00am';
const countOccurrences = (str: string) =>
Object.entries<number>(
str
.replace(/[\n\r–—/]+/g, ' ')
.replace(/[^\p{L}\p{N}\p{M}\p{Zs}\p{So}\s-]+/ug, '')
.replace(/\s\s+/g, ' ')
.split(' ')
.reduce((obj: any, word: string) => (
word in obj ? obj[word]++ : obj[word] = 1,
obj
), {})
)
.sort((a, b) => b[1] - a[1])
.map(x => ({ word: x[0], count: x[1] }));
console.log(countOccurrences(str));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment