There are a number of ways we can split a number into digits in JavaScript. One of the simplest ways to do this is to convert the number into a string, iterate over it, and create a new array of digits. Here is the code of how to do this, and then we will explain what is going on afterward:
var someNumber = 5436;
var numberToString = someNumber.toString();
var digits = [];
for( var i=0; i<numberToString.length; i++ ){
digits[i] = Number(numberToString.charAt(i));
}
In the code above, you will notice that we first convert the number to a string using the toString() method. We then make use of the charAt() method to get each individual digit, and then convert that digit back to a number using the Number() method, and finally add that number to our array. And that’s it.
Let’s put our code above into a function to make it really easy to split a number into digits.
function splitNumberToDigits(num){
var numberToString = num.toString();
var digits = [];
for( var i=0; i<numberToString.length; i++ ){
digits[i] = Number(numberToString.charAt(i));
}
return digits;
};
And now, lets show an example of this function to see it in action:
function splitNumberToDigits(num){
var numberToString = num.toString();
var digits = [];
for( var i=0; i<numberToString.length; i++ ){
digits[i] = Number(numberToString.charAt(i));
}
return digits;
};
console.log(splitNumberToDigits(100));
console.log(splitNumberToDigits(213));
#Output:
[1, 0, 0]
[2, 1, 3]
Let’s go over another way to do this that requires a lot less code.
Using the Map Method and Spread Operator to Split a Number into Digits in JavaScript
Another really simple way that requires less code to split a number into digits in JavaScript is to make use of the map() method, the … spread operator, and String() method.
Here is the simple code that split a number into digits using these methods.
var digitsArray = [...String(5463)].map(Number);
Where 5463 in the code above can be any number you want.
Let’s put this in a function and show this in action with a couple of examples:
function splitNumberToDigits(num){
return [...String(num)].map(Number);
};
console.log(splitNumberToDigits(100));
console.log(splitNumberToDigits(213));
#Output:
[1, 0, 0]
[2, 1, 3]
Hopefully this article has been useful for you to learn how to split a number into digits in JavaScript.