DEV Community

Cover image for Separate a multi-digit integer into a single-digit array.
Maria Abelarda Diaz
Maria Abelarda Diaz

Posted on

Separate a multi-digit integer into a single-digit array.

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]
Enter fullscreen mode Exit fullscreen mode

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];
Enter fullscreen mode Exit fullscreen mode

If you want to share more ways to do this, please do so in the comments, with some explanation for us beginners.

Top comments (1)

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

Short version of string one:

const num = 123
const int = [...''+num].map(i=>+i)
Enter fullscreen mode Exit fullscreen mode