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

212
Vistas
counting characteres in string using object

I'm trying to count the characters in a string using an object. This is the function that I wrote:

function maxChar(str) {

    let obj = {}   

    for(let char of str){
        if(obj[char]){
            obj[char] += 1 
        }           
        obj[char] = 1            
    }  
    console.log(obj)
}

When I run the function with the string "Hello There!" it returns:

{
   : 1,
  !: 1,
  e: 1,
  H: 1,
  h: 1,
  l: 1,
  o: 1,
  r: 1,
  T: 1
}

Which of course is not counting properly. If I change the if statement like this:

function maxChar(str) {

    let obj = {}   

    for(let char of str){
        if(!obj[char]){
            obj[char] = 1           
        }           
        obj[char] += 1      
    }  
    console.log(obj)
}

It returns


{
   : 2,
  !: 2,
  e: 4,
  H: 2,
  h: 2,
  l: 3,
  o: 2,
  r: 2,
  T: 2
}

Are not tboth functions supposed to do the same? why is this happening?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your first version looks like this. I've added some comments:

    for(let char of str){
        if(obj[char]){
            obj[char] += 1  // this happens only when the `if` condition is met
        }           
        obj[char] = 1 // this happens all the time, regardless of the `if` condition
    } 

That version will always reset the character count to 1. Even if it had just briefly incremented the count to 2, it will still reset it to 1 immediately after having done so.

One fix (that most closely matches your original code) could be:

    for(let char of str){
        if(obj[char]){
            obj[char] += 1
        } else {
            obj[char] = 1
        }
    } 
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