A number can be converted into an array of its individual digits using different JavaScript approaches.
- Convert the number to a string and process each digit.
- Extract digits using mathematical operations.
- Use built-in methods or recursion depending on the requirement.
Approach 1: Using Array.from() Method
The Array.from() method creates an array from an iterable. By converting the number to a string, each digit can be converted into a separate array element.
let num = 235345;
let arr = Array.from(String(num), Number);
console.log(arr);
Output
[ 2, 3, 5, 3, 4, 5 ]
Approach 2: Using Mathematical Operations
In this approach, the modulo (%) operator extracts the last digit of the number, while Math.floor() removes the last digit. The extracted digits are added to the beginning of the array.
let num = 12345;
let arr = [];
while (num > 0) {
arr.unshift(num % 10);
num = Math.floor(num / 10);
}
console.log(arr);
Output
[ 1, 2, 3, 4, 5 ]
Approach 3: Using for Loop
A for loop can iterate through the string representation of the number and add each digit to a new array.
const num = 12345;
const arr = [];
const str = String(num);
for (let i = 0; i < str.length; i++) {
arr.push(Number(str[i]));
}
console.log(arr);
Output
[ 1, 2, 3, 4, 5 ]
Approach 4: Using split() Method
The split() method splits the string representation of the number into individual characters. The map(Number) converts each character into a number.
const number = 235345;
const res = number.toString().split('').map(Number);
console.log(res);
Output
[ 2, 3, 5, 3, 4, 5 ]
Approach 5: Using Recursion
Recursion can repeatedly remove the last digit and construct the array from the remaining digits.
function fun(num) {
if (num === 0) {
return [];
}
const dig = fun(Math.floor(num / 10));
dig.push(num % 10);
return dig;
}
const num = 235345;
const res = fun(num);
console.log(res);
Output
[ 2, 3, 5, 3, 4, 5 ]