Counting and Sorting Words
Counting And Sorting Words In A String Using JavaScript replace, forEach, and sort Method
If we are given an essay, a short story, a lyrics of a song, or a novel or even the King James bible and we want to know which words has the most occurences, we can use the JavaScript replace, split, for Each, and sort method.
Suppose we are given the following string:
“The results were a dead tie for these comfy yet controversial footwear item! In a 4:4 vote, advisors were divided on whether or not they’d ever been seen in public in Crocs. With varied results we had several responses of …no. just no.as well as team croc forever. So what do you think!? Crisp crocs or crocs with charms? Bring it up in your next 1:1 with your advisor to break the ice!”
We can have an array of words with the number of times it appear on the paragraph and it will be sorted from the most number of occurrences to the least.
First ,we have to remove some punctuation marks so that they will not interfere with the counting. for example the word “and” and “and,” will be counted differently if we will not do that. Then we convert all letters to lower case because the word “The” and “the” will be counted separately and we do not want that. Then we separate the words and put them into an array.
Then we create an empty array where we can placed all the words that we found. We, then sort out this words from highest number of occurrences to the lowest and put them in a new array.
Here is the sample code:

// Example
const g = “The results were a dead tie for these comfy yet controversial footwear item! In a 4:4 vote, advisors were divided on whether or not they’d ever been seen in public in Crocs. With varied results we had several responses of …no. just no.as well as team croc forever. So what do you think!? Crisp crocs or crocs with charms? Bring it up in your next 1:1 with your advisor to break the ice! “;
const result = countWords(g);
console.log(result);
Result:
{
‘11’: 1,
‘44’: 1,
in: 4,
crocs: 3,
with: 3,
the: 2,
results: 2,
were: 2,
a: 2,
or: 2,
your: 2,
dead: 1,
tie: 1,
for: 1,
these: 1,
comfy: 1,
yet: 1,
controversial: 1,
footwear: 1,
item: 1,
vote: 1,
advisors: 1,
divided: 1,
on: 1,
whether: 1,
not: 1,
theyd: 1,
ever: 1,
been: 1,
seen: 1,
public: 1,
varied: 1,
we: 1,
had: 1,
several: 1,
responses: 1,
of: 1,
no: 1,
just: 1,
noas: 1,
well: 1,
as: 1,
team: 1,
croc: 1,
forever: 1,
so: 1,
what: 1,
do: 1,
you: 1,
think: 1,
crisp: 1,
charms: 1,
bring: 1,
it: 1,
up: 1,
next: 1,
advisor: 1,
to: 1,
break: 1,
ice: 1,
‘’: 1
}
In this result, the word with the highest number of occurrences is “in” which has a count of 4, followed by “crocs” and “with” which both has three. Take note that 1:1 and 4:4 becomes 11 and 44, it is because we remove the semicolon when we remove all the punctuation marks.