Separate a multi-digit integer into a single-digit array.
Maria Abelarda Diaz
Posted on April 26, 2023
I am sure there are several more ways to turn a multi-digit integer, like 123, into a single-digit array, but in this post, two ways are going to be suggested:
1. Turn it to string.
Here, we use the JS method toString() first to turn the integer into a string. Then, we split it with split(''). At this step, we have an array of strings. So, we can manipulate the array with a for loop or with a map() to turn every string into a number. We will use a map:
const num = 123;
let str = num.toString().split(''); // ["1", "2", "3"]
let int = str.map((single)=>parseInt(single)); // [1,2,3]
2. With math:
For the second suggestion, we are taking the multi-digit integer and putting it in a while loop. The condition is: "while num is true" or "while num exists" we use the modulus of 10 to get the remainder every time we divide the integer by 10. We can use either Math.floor() or parseInt() to make sure we have an integer to push to our array.
let num = 123
let arrNum = [];
while(num){
arrNum.push(num%10);
num = Math.floor(num/10); // remember we can use parseInt() too.
}
console.log(arrNum) // [1,2,3];
If you want to share more ways to do this, please do so in the comments, with some explanation for us beginners.
Posted on April 26, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
August 26, 2024
February 27, 2024