Issue
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));
Solution
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 to0
(this check fails and is why your function is returning the unformatted phone number) but you want to compare the index, so change this toi === 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 😉
Answered By – Ro Milton
Answer Checked By – Cary Denson (BugsFixing Admin)