Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getTokens(rawString) {
- // NB: `.filter(Boolean)` removes any falsy items from an array
- return rawString.toLowerCase().split(/[ ,!.";:-]+/).filter(Boolean).sort();
- }
- // counting the amount of time a word/character pops up and sorting them and to show which word/character comes up the most.
- function mostFrequentWord(text) {
- let words = getTokens(text);
- let wordFrequencies = {};
- // putting the strings into a loop and counting the frequency of the words/characters in the string or leaving them as 1 if the character
- only comes up once
- for (let i = 0; i <= words.length; i++) {
- if (words[i] in wordFrequencies) {
- wordFrequencies[words[i]]++;
- } else {
- wordFrequencies[words[i]] = 1;
- }
- }
- // starting from index 0 and adding the counts to wordFrequencies.
- let currentMaxKey = Object.keys(wordFrequencies)[0];
- let currentMaxCount = wordFrequencies[currentMaxKey];
- //making currentMaxKey equal the count of "word" and equalling the total into the frequencies and then returning the currentMaxKey.
- for (let word in wordFrequencies) {
- if (wordFrequencies[word] > currentMaxCount) {
- currentMaxKey = word;
- currentMaxCount = wordFrequencies[word];
- }
- }
- return currentMaxKey;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement