- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements