How to use a for loop to iterate through the string representation In Javascript
The for loop approach involves converting the number to a string, iterating through each character of the string, and converting each character back to a number. These numbers are then pushed into an array, resulting in an array of the number’s digits.
Example: In this example we converts a number to a string, iterates over each character, converts it back to a number, pushes each digit into an array, and then logs the resulting array of digits to the console.
const number = 12345;
const array = [];
const numStr = String(number);
for (let i = 0; i < numStr.length; i++) {
array.push(Number(numStr[i]));
}
console.log(array);
Output
[ 1, 2, 3, 4, 5 ]
How to convert a number into array in JavaScript ?
In this article, we have been given a number and the task is to convert the given number into an array using JavaScript.
These are the following methods by using these we can solve this problem:
Table of Content
- Using Array.from() Method
- Using map() Method
- Using reduce() function
- Using Lodash _.toArray() Method
- Using mathematical operations
- Using a for loop to iterate through the string representation