Convert Array to Phone Number String in JavaScript



To convert an array to a phone number string in JavaScript can be done by formatting the array elements into the desired phone number pattern.

Following are the steps to learn how to convert array to phone number string in Javascript ?

  • Ensure that the array has the correct number of elements (usually 10 for a standard phone number).
  • Join the elements of the array into a single string.
  • Format the string into the desired phone number pattern, such as (XXX) XXX-XXXX.

Let us understand through some sample example of I/O Scenario ?

Sample Input -

const arr = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; 

Sample Output ?

const output = '(987) 654-3210'; 

Converting array to phone number string in Javascript

Converting array to phone number string in JavaScript is quite easy. Let's learn through the following programs ?

Program to Handle Different Lengths

In this program, we have initialized exactly 10 array elements. So, it ensures the input array has exactly 10 elements. then joins the array elements into a single string and formats it into a phone number pattern (XXX) XXX-XXXX, returning the formatted string.

Example

function arrayToPhoneNumber(arr) { if (arr.length !== 10) { return "Invalid input: Array must contain exactly 10 elements."; } const str = arr.join(''); return `(${str.slice(0, 3)}) ${str.slice(3, 6)}-${str.slice(6, 10)}`; } const phoneArray = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; const phoneNumber = arrayToPhoneNumber(phoneArray); console.log(phoneNumber); 

Output

Following is the output of the above program ?

(987) 654-3210 

Program to Handle Edge Cases

Here, we have intialized 9 array elements but the requirement is that we should have exact 10 number. So, it returns an error message as Invalid input.

Example

function arrayToPhoneNumber(arr) { if (!Array.isArray(arr) || arr.length !== 10 || !arr.every(num => !isNaN(num) && num !== null && num !== undefined)) { return "Invalid input: Array must contain exactly 10 valid digits"; } const str = arr.join(''); return `(${str.slice(0, 3)}) ${str.slice(3, 6)}-${str.slice(6, 10)}`; } const phoneArray = [4, 5, 1, 3, 8, null, 7, 5, 2, 0]; const phoneNumber = arrayToPhoneNumber(phoneArray); console.log(phoneNumber); 

Output

Following is the output of the above program ?

Invalid input: Array must contain exactly 10 valid digits 
Revathi Satya Kondra
Revathi Satya Kondra

Technical Content Writer, Tutorialspoint

Updated on: 2025-01-30T17:48:53+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements
close