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

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

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 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