JavaScript Coding Challenge: "Create a Phone Number"

JCC Create a Phone Number Image

It's been a while since I did a JavaScript Coding Challenge so I thought that I should bring it back this Friday (let me know if you like these and I'll add a new one each Friday). 😄

I searched on Codewars and found a challenge to Create a Phone Number out of an array. This is what it says:

Write a function that accepts an array of 10 integers (between 0 and 9), that returns a string of those numbers in the form of a phone number.

Example:

createPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]) // => returns "(123) 456-7890"

As you can see this is very easy, but sometimes I love doing these simple challenges in order to relax a little bit, and hopefully you'll learn something new too! It's a win-win situation! 😄

Note: I highly recommend you solve this challenge on your own before moving forward. You'll learn much more by doing so!

I found two solutions for this challenge:

The First Solution

This is the "obvious one" where we're going to use the .slice and .join methods in order to take out the values that we need from the array between the specified indexes. Also we'll use the string template literals in order to have a cleaner code:

function createPhoneNumber(arr) {
    return `(${arr.slice(0, 3).join('')}) ${arr.slice(3, 6).join('')}-${arr.slice(6).join('')}`;
}

Or we can create a string at the beginning by .joininig the characters and then using .substring to take the specific ones out:

function createPhoneNumber(arr) {
    let str = arr.join('');
    return `(${str.substring(0, 3)}) ${str.substring(3, 6)}-${str.substring(6)}`;
}

The Second Solution

For this one we'll create a mask that will be used to .replace (insert) the numbers inside the string. Note that the .replace function will find and replace only the first occurrence of x in this case (which is what we want), then it will move on to the next x in the next iteration and so on...

function createPhoneNumber(arr) {
    let mask = '(xxx) xxx-xxxx';

    arr.forEach(item => {
        mask = mask.replace('x', item);
    });

    return mask;
}

Conclusion

As I said, this was an easy challenge! 👍

I dare you to find another solution for it. Maybe by using RegExp? 😉

Let me know what you get!

Happy Coding! 😇

Tagged with javascript, challenge, beginner, codewars, array, slice, join