This content originally appeared on DEV Community and was authored by Maria Abelarda Diaz
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.
This content originally appeared on DEV Community and was authored by Maria Abelarda Diaz
Maria Abelarda Diaz | Sciencx (2023-04-26T20:00:05+00:00) Separate a multi-digit integer into a single-digit array.. Retrieved from https://www.scien.cx/2023/04/26/separate-a-multi-digit-integer-into-a-single-digit-array/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.