-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathcount-words.js
More file actions
56 lines (39 loc) · 1.65 KB
/
count-words.js
File metadata and controls
56 lines (39 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
Count the number of times a word appears in a given string.
Write a function called countWords that
- takes a string as an argument
- returns an object where
- the keys are the words from the string and
- the values are the number of times the word appears in the string
Example
If we call countWords like this:
countWords("you and me and you") then the target output is { you: 2, and: 2, me: 1 }
To complete this exercise you should understand
- Strings and string manipulation
- Loops
- Comparison inside if statements
- Setting values on an object
## Advanced challenges
1. Remove all of the punctuation (e.g. ".", ",", "!", "?") to tidy up the results
2. Ignore the case of the words to find more unique words. e.g. (A === a, Hello === hello)
3. Order the results to find out which word is the most common in the input
*/
function countWords(str) {
const words = str
.toLowerCase()
.replace(/[^a-zA-Z0-9\s]/g, '') // replace punctuation with space
.trim()
.split(/\s+/); // split on any white space
const countObj = Object.create(null);
for (const word of words) {
countObj[word] = (countObj[word] || 0) + 1;
}
// `Object.entries()` converts object to array
const sortedArray = Object.entries(countObj).sort((a, b) => b[1] - a[1]);
// `Object.fromEntries()` coverts the sorted array to object
return Object.fromEntries(sortedArray);
}
console.log(countWords("you? and! me, and you. me me me me hello Me"));
console.log(countWords(" Hello World "));
console.log(countWords("constructor constructor"));
console.log(countWords("Hello,World! Hello World!"));