Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 26, 2023 08:00 pm GMT

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]

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 = 123let 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.


Original Link: https://dev.to/laladiaz/separate-a-multi-digit-integer-into-a-single-digit-array-1ll2

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To