JavaScript – Split Number into Digits

Sometimes we have the requirement to split a given number of digits. Let’s discuss some of the ways by which this can be done.

Using toString() and split()

In this approach toString() converts the number to a string, split() is then used to split the string into an array of characters, and finally map(Number) converts each character back to a number.

codepen link

function splitNumberIntoDigits(num) {
    return num
        .toString()
        .split("")
        .map(Number);
}

// Example usage
const number = 1256;
const digits = splitNumberIntoDigits(number);
console.log(digits);

Output

[1,2,5,6]

Using direct iteration & push()

Codepen link

This method involves converting the number to a string, iterating through each character in the string, and then pushing the numeric value of each character into an array.

let num = 32456;
let digits = [];

for (let i = 0; i < num.toString().length; i++) {
    digits.push(Number(num.toString()[i]));
}

console.log(digits);

Output

[3,2,4,5,6]

Similar Reads