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.
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()
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
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String