Converting array to phone number string in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of exactly 10 positive integers, arr, as the first and the only argument.

Our function should then return a string which is in the format of a phone number string.

For example, if the input to the function is −

Input

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

Output

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

Example

Following is the code −

 Live Demo

const arr = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
const createNumber = (arr = []) => {
   let res = '';
   arr = arr.map(String);
   res += `(${arr[0]+arr[1]+arr[2]}) `;
   res += `${arr[3] + arr[4] + arr[5]}-`;
   res += arr[6] + arr[7] + arr[8] + arr[9];
   return res;
};
console.log(createNumber(arr));

Output

(987) 654-3210

Updated on: 22-Apr-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements