Open In App

Split a number into individual digits using JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will get some input from the user by using <input> element and the task is to split the given number into the individual digits with the help of JavaScript. These two approaches are discussed below:

Examples of splitting a number into individual digits using JavaScript

1. Using number.toString() and split(”)

In this approach number.toString() converts the number to a string, split(”) splits the string into an array of characters, and map(Number) converts each character back to a number. This approach effectively splits the number into its digits.

Example: This example implements the above approach.

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

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

Output
[ 1, 2, 3, 4, 5 ]

2. Direct Character Iteration and Array Push

First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Visit every character of the string in a loop on the length of the string and push the character in the array(res) by using push() method

Example: This example implements the above approach. 

Javascript
function GFG_Fun() {
    let str = "123456";

    let res = [];

    for (
        let i = 0, len = str.length;
        i < len;
        i += 1
    ) {
        res.push(+str.charAt(i));
    }

    console.log(res);
}

GFG_Fun();

Output
[ 1, 2, 3, 4, 5, 6 ]

3. Splitting String into Array of Characters

First take the element from input element in string format (No need to convert it to Number) and declare an empty array(var res). Split the string by using split() method on (”) and store the splitted result in the array(str). 

Example: This example implements the above approach. 

JavaScript
function GFG_Fun() {
    let n = "123456";
    let str = n.split('');
    console.log(str);
}

GFG_Fun();

Output
[ '1', '2', '3', '4', '5', '6' ]

4. Using Modulo Operator

We will be using modulo operator to get the last digit of the number and then divide the number by 10 to calculate the remaining ones and to repeat this we will use the while loop, this iteration will continue to run until the number becomes zero.

JavaScript
function GFG_Fun() {
    let number = 123456;
    let digit = [];

    while (number > 0) {
        digit.unshift(number % 10);
        number = Math.floor(number / 10);
    }
    console.log(digit);
}

GFG_Fun();

Output
[ 1, 2, 3, 4, 5, 6 ]


Last Updated : 19 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads