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

219
Vistas
How do I get my 'for loop' to return the characters I am trying to push?

I am learning the fundamentals of JavaScript currently but am realizing there are definite gaps in my knowledge. I recently started attempting challenges on Codewars when this issue became much more apparent. My latest struggle has been attempting to get this 'for loop' to push characters into an array of numbers in order to format it like a phone number. As many different solutions as I have tried, none of them actually do what I am trying to accomplish. Any help figuring out exactly where I'm going wrong here and what holes are in my logic would be appreciated. My best attempt is this:

const createPhoneNumber = (phoneNumber) => {
    let formattedNumber = [];
    formattedNumber.push(phoneNumber)
    for (let i = 0; i < formattedNumber.length; i++) {
        if (formattedNumber[i] === 0) {
            formattedNumber.push('(')
        }
        if (formattedNumber[i] === 2) {
            formattedNumber.push(')')
        }
        if (formattedNumber[i] === 5) {
            formattedNumber.push('-')
        }
    }
    return(formattedNumber.toString());
}

console.log(createPhoneNumber(1234567890));

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

0

Some feedback:

  • You're inserting one item into the array formattedNumber.push(phoneNumber) then looping through it, so there's only one iteration
  • Instead, you could convert the number to a string and iterate using its length
  • The check formattedNumber[i] === 0 is comparing the value to 0 (this check fails and is why your function is returning the unformatted phone number) but you want to compare the index, so change this to i === 0
  • At the end of the function you're using toString() to join the characters back together but this will include commas between values, instead use .join('')

const createPhoneNumber = (phoneNumber) => {
    const phoneNumberStr = (phoneNumber).toString(); 
    let formattedNumber = [];
    for (let i = 0; i < phoneNumberStr.length; i++) {
        if (i === 0) {
            formattedNumber.push('(')
        }
        if (i === 2) {
            formattedNumber.push(')')
        }
        if (i === 5) {
            formattedNumber.push('-')
        }
        formattedNumber.push(phoneNumberStr[i]);
    }
    return(formattedNumber.join(''));
};

console.log(createPhoneNumber(1234567890))

Also, you can use .reduce() to achieve the same thing, it's a convenient function that iterates through an array, and passes a value from one iteration to the next:

const createPhoneNumber = (phoneNumber) => 
    (phoneNumber).toString().split('').reduce((acc, char, i) => {
      let pre = ''; 
      if (i == 0) { pre = '('; }
      if (i == 2) { pre = ')'; }
      if (i == 5) { pre = '-'; }
      return `${acc}${pre}${char}`;
    }, '');

console.log(createPhoneNumber(1234567890));

BTW, I think your question was downvoted because you didn't provide an expected output or more details of the error 😉

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