Reputation: 57
for example:
"themselves"
, "Themselves"
or " THEMSelveS "
(note the leading and trailing spaces), should be
counted as themselves: 3
My code:
const { readFile, readFileSync } = require('fs');
let file = 'C:\Users\eeroj\source\repos\Nodejs\pish\pish';
function countRepeatedWords(sentence) {
let words = sentence.split(" ");
let wordMap = {};
for (let i = 0; i < words.length; i++) {
let currentWordCount = wordMap[words[i]];
let count = currentWordCount ? currentWordCount : 0;
wordMap[words[i]] = count + 1;
}
const sortedEntries = Object.entries(wordMap).sort(([a,], [b,]) => a.localeCompare(b));
const sortedWordMap = Object.fromEntries(sortedEntries);
return sortedWordMap
return wordMap;
}
words = readFileSync(file).toString();
console.log(countRepeatedWords(words));
Upvotes: 0
Views: 66
Reputation: 844
You can use the toLowerCase()
function:
let words = sentence.split(" ");
let wordMap = {};
for (let i = 0; i < words.length; i++) {
const key = words[i].toLowerCase();
let currentWordCount = wordMap[key];
let count = currentWordCount ? currentWordCount : 0;
wordMap[key] = count + 1;
}
I would also suggest you to use for of
loop, remove empty cells, define everything as const
and use Nullish coalescing:
const words = sentence.split(" ").filter(word => word); // returns if word isn't empty
const wordMap = {};
for (let word of words) {
const key = word.toLowerCase();
const currentWordCount = wordMap[key];
wordMap[key] = (currentWordCount ?? 0) + 1;
}
Upvotes: 1
Reputation: 816910
Convert every word to lower case with toLowerCase()
and trim()
spaces.
for (let word of words) {
word = word.trim().toLowerCase();
wordMap[word] = (wordMap[word] ?? 0) + 1;
}
Notes:
.trim()
you could also just split my one or more spaces: let words = sentence.split(/ +/)
.Map
instead of an object or at least use Object.create(null)
to not mix your data with built in properties.Upvotes: 0