Skip to content

Instantly share code, notes, and snippets.

@sharepointoscar
Created February 16, 2018 21:21
Show Gist options
  • Save sharepointoscar/8297e409804769b75e85d4a89f3a27cb to your computer and use it in GitHub Desktop.
Save sharepointoscar/8297e409804769b75e85d4a89f3a27cb to your computer and use it in GitHub Desktop.
Find total occurrences of a word within a sentence. Output word and count.
module.exports = {
getText: function(req,res){
var _text = req.param('text');
var _splitUpWords = _text.split(' ');
var _wordCount = {};
// store all words in an object
for (let index = 0; index < _splitUpWords.length; index++) {
//{korea:0,trip:2}
_wordCount[_splitUpWords[index]] = 0;
}
console.log('_wordCount: '+ JSON.stringify(_wordCount,null,2));
// iterate through the original sentence we split into words.
// find multiple ocurrences of a word
// lastly update the word count tracker object.
for (let index = 0; index < _splitUpWords.length; index++) {
const word = _splitUpWords[index];
console.log('the word being checked: '+ word);
var _currentWord = _splitUpWords.filter(function(it) {return it === word;});
console.log('_currentWord: '+ _currentWord);
var _currentWordCount = _currentWord.length;
console.log('_currentWordCount: '+ _currentWordCount);
//update the _wordCount tracker
_wordCount[word] = _currentWordCount;
}
console.log('_wordCount: '+ JSON.stringify(_wordCount,null,2));
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment