Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

347
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda