Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

344
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda