Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!