-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution10.js
31 lines (28 loc) · 923 Bytes
/
solution10.js
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
const topWord = (string) => {
//turn string to lowercase and an array
let words = string.toLowerCase('').split(' ')
let wordDict = {}
//create object to store words and the word's count. Do this in a key value pair
for (let i = 0; i < words.length; i++) {
if (wordDict.hasOwnProperty(words[i])) {
wordDict[words[i]] = wordDict[words[i]] + 1
} else {
wordDict[words[i]] = 1
}
}
//go through the object to find the word with the highest frequency.
//in other words, return the key from the key value pair with the highest value
let max = 0
let maxKey = ''
for (let word in wordDict) {
if (wordDict[word] > max) {
max = wordDict[word]
maxKey = word
}
}
//return the key
return maxKey
}
console.log(topWord('The cat sat on the mat'))
console.log(topWord('The cat cat cat sat on the mat'))
console.log(topWord('The cat sat sat sat on the mat mat mat'))