Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
Count the same words regardless of the case sensitivity, or padding

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));
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report

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.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!