I assumed the US phone number format that is (XXX) XXX-XXXX
constformatNumber=numbers=>{letphoneNumber="";// prerequisites:// - input must be an array// - with 10 elements// - each element will be a single digit numberif(Array.isArray(numbers)&&numbers.length===10&&numbers.every(n=>n>-1&&n<10)){// break the phone number into parts and generate the formmated stringconstareaCode=numbers.slice(0,3).join('');constfirstPart=numbers.slice(3,6).join('');constsecondPart=numbers.slice(6).join('');phoneNumber=`(${areaCode}) ${firstPart}-${secondPart}`;}returnphoneNumber;}
Live demo on CodePen (with an alternative version in one line).
JavaScript
Live demo on CodePen (with an alternative version in one line).
Why the one line solution?
No real reason. Both do the same, the first one is more verbose and easier to understand. I deleted the one-line one to avoid any confusion.