0

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));
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    Convert every word to lower case with `toLowerCase()` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase – Felix Kling Sep 03 '21 at 09:39
  • 1
    Does this answer your question? [How to do case insensitive string comparison?](https://stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison) – pilchard Sep 03 '21 at 09:41
  • People are so fast with their answers :D yeah, toLowerCase should let you handle each word as lowercase regardless of how many letters are uppercase when being read. – DragonInTraining Sep 03 '21 at 09:42
  • @eerojyrgenson you should read the [duplicate](https://stackoverflow.com/questions/2140627/how-to-do-case-insensitive-string-comparison), there are more robust solutions available with more explanation than what has been provided here. – pilchard Sep 03 '21 at 13:22

2 Answers2

1

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;
}
Liad
  • 789
  • 4
  • 10
0

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:

  • Instead of using .trim() you could also just split my one or more spaces: let words = sentence.split(/ +/).
  • You might want to use a Map instead of an object or at least use Object.create(null) to not mix your data with built in properties.
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143