I want to convert an integer, say 12345
, to an array like [1,2,3,4,5]
.
I have tried the below code, but is there a better way to do this?
var n = 12345; var arr = n.toString().split(''); for (i = 0; i < arr.length; i++) arr[i] = +arr[i] | 0;
To split a number into an array:Use the Array. from() method to convert the string into an array of digits. Use the map() function to convert each string in the array to a number.
Apache Commons Lang's ArrayUtils class provides a toPrimitive() method that can convert an Integer object array to array of primitive ints. We need to convert a Set<Integer> to a primitive integer array first. We can use Set. toArray() for easy conversion.
Step 1 − Divide the decimal number to be converted by the value of the new base. Step 2 − Get the remainder from Step 1 as the rightmost digit (least significant digit) of new base number. Step 3 − Divide the quotient of the previous divide by the new base.
This single line will do the trick:
Array.from(String(12345), Number);
const numToSeparate = 12345; const arrayOfDigits = Array.from(String(numToSeparate), Number); console.log(arrayOfDigits); //[1,2,3,4,5]
1- String(numToSeparate)
will convert the number 12345 into a string, returning '12345'
2- The Array.from()
method creates a new Array instance from an array-like or iterable object, the string '12345' is an iterable object, so it will create an Array from it.
3- But, in the process of automatically creating this new array, the Array.from()
method will first pass any iterable element (every character in this case eg: '1', '2') to the function we set to him as a second parameter, which is the Number
function in this case
4- The Number
function will take any string character and will convert it into a number eg: Number('1')
; will return 1
.
5- These numbers will be added one by one to a new array and finally this array of numbers will be returned.
Summary
The code line Array.from(String(numToSeparate), Number);
will convert the number into a string, take each character of that string, convert it into a number and put in a new array. Finally, this new array of numbers will be returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With