-
-
Notifications
You must be signed in to change notification settings - Fork 286
Expand file tree
/
Copy pathcount-words.js
More file actions
51 lines (36 loc) · 1.44 KB
/
count-words.js
File metadata and controls
51 lines (36 loc) · 1.44 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
/*
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 arr = str.replace(/[^a-zA-Z0-9\s]/g, '').toLowerCase().split(" ")
let countObj = {};
for (const item of arr) {
if (countObj[item]) {
countObj[item] = countObj[item] + 1
} else {
countObj[item] = 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"));