JavaScript: Converts a specified number to an array of digits
JavaScript fundamental (ES6 Syntax): Exercise-7 with Solution
Write a JavaScript program to convert a specified number into an array of digits.
Note: Convert the number to a string, using the spread operator (...) to build an array.
- Use Math.abs() to strip the number's sign.
- Convert the number to a string, using the spread operator (...) to build an array.
- Use Array.prototype.map() and parseInt() to transform each value to an integer.
Sample Solution:
JavaScript Code:
const digitize = n => [...`${n}`].map(i => parseInt(i));
console.log(digitize(123));
console.log(digitize(1230));
Sample Output:
[1,2,3] [1,2,3,0]
Pictorial Presentation:
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-7 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to target a given value in a nested JSON object, based on the given key.
Next: Write a JavaScript program to filter out the specified values from an specified array. Return the original array without the filtered values.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join