-
-
Notifications
You must be signed in to change notification settings - Fork 283
Expand file tree
/
Copy pathcount-words.js
More file actions
39 lines (30 loc) · 1.23 KB
/
count-words.js
File metadata and controls
39 lines (30 loc) · 1.23 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
/*
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(string) {
const noPunctuationStr = string.replace(/[.,!?]/g, "");
const wordArray = noPunctuationStr.split(" ");
let wordCount = new Map();
for (let word of wordArray) {
wordCount.set(word, (wordCount.get(word) || 0) + 1);
}
const sortedWordCount = [...wordCount.entries()].sort((a, b) => b[1] - a[1]);
return sortedWordCount;
}