Skip to content

Commit eac17d1

Browse files
committed
count-words function
1 parent 2c9e1aa commit eac17d1

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Sprint-2/stretch/count-words.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,3 +26,23 @@
2626
2727
3. Order the results to find out which word is the most common in the input
2828
*/
29+
function countWords(str) {
30+
let obj = {}; // create an empty object
31+
32+
const arr = str
33+
.toLowerCase() // make a string lowercase completely
34+
.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g, "") // delete any regex symbols from strings
35+
.split(" "); // convert string to an array by splitting the string into words by using " " as a delimiter
36+
37+
for (const word of arr) {
38+
// looping through the array
39+
obj[word] = (obj[word] || 0) + 1; // fill up the empty object with keys (words) and values (the number of times the word appears in the value)
40+
}
41+
let entries = Object.entries(obj); // convert oject into an array to be able to sort it
42+
let sorted_obj = entries.sort((a, b) => b[1] - a[1]); // sorting entries in descending order
43+
44+
return Object.fromEntries(sorted_obj); // convert the sorted array into object again
45+
}
46+
47+
const str = "we meet Dan,,, to meet Dan Dan dan,";
48+
console.log(countWords(str));

0 commit comments

Comments
 (0)