-
-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathcount-words.js
More file actions
48 lines (37 loc) · 1.34 KB
/
count-words.js
File metadata and controls
48 lines (37 loc) · 1.34 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
/*
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 wordArray = string
.toLowerCase()
.split(/[.,!? ]+/)
.filter(Boolean);
const wordCount = {};
for (let word of wordArray) {
wordCount[word] = (wordCount[word] || 0) + 1;
}
const sortedWordCount = Object.fromEntries(
[...Object.entries(wordCount)].sort(
([wordA, countA], [wordB, countB]) => countB - countA
)
);
return sortedWordCount;
}
console.log(countWords("you and me and ? ? . . you "));