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

340
Views
How to check how many times character from string appears?

I want to count how many times each letter from params appears in this string. What am I doing wrong?

function solution(word) {
    let temp = {}
    for(const c of word) {
      temp[c]++;
      console.log(temp[c])
  }
  
}

solution("PAPAYA")

It should output me numbers below for each letter, but i keep getting NaN

1 // P appeared once
1 // A appeared once
2 // P appeared second time
2 // A appeaed second time
1 // Y Once
3 // A appeared third time

so it should look like

{
  A: 3,
  P: 2,
  Y: 1
}
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Here is an easy solution without changing your code to much

function solution(word) {
    let temp = {}
    for(const c of word) {
      if (temp[c] === undefined)
        temp[c] = 1;
       else temp[c]++;
  }
  console.log(temp)
}

solution("PAPAYA")

about 4 years ago · Juan Pablo Isaza Report

0

At the start, no properties are set on the object, so accessing the value for a character results in undefined. Incrementing that produces NaN. You will need to specifically handle that case for the first time a letter appears.

function solution(word) {
    let temp = {}
    for(const c of word) 
      temp[c] = (temp[c] || 0) + 1;
    return temp;
}
console.log(solution("PAPAYA"));

about 4 years ago · Juan Pablo Isaza Report

0

set temp[c] to a number (0) first for example

if (NaN(temp[c])) temp[c] = 0

The reason for this is because if you do ++ on undefined, it is still undefined, and therefore, not a number

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!