How to convert an integer to an array of numbers

I want to convert an integer, say 12345 , to an array like [1,2,3,4,5] . I tried the code below, 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 ; 
+10
javascript
source share
7 answers

I would go with

 var arr = n.toString(10).replace(/\D/g, '0').split('').map(Number); 

You can omit replace if you are sure that n does not have decimals.

+11
source share
 var n = 12345; var arr = ('' + n).split('').map(function(digit) {return +digit;}); 

However, the map function is only supported by the latest browsers.

+6
source share

I would do this to avoid using strings when you don't need them:

 var n = 12345; var arr = []; while(n>0){arr.unshift(n%10);n=n/10|0;} 
+3
source share

**** 2019 Answer ****

 Array.from(String(12345), Number); 

example

 const numToSeparate = 12345; const arrayOfDigits = Array.from(String(numToSeparate), Number); console.log(arrayOfDigits); //[1,2,3,4,5] 
+3
source share

I first converted the number to a string, and then used Array.from () to convert the string to an array.

 let dataArray = Array.from(value.toString()); 
0
source share

Run fragment:

 const n = 12345; let toIntArray = (n) => ([...n + ""].map(Number)); console.log(toIntArray(n)); 
0
source share

First, the integer is converted to string & then to array. Using the map function, individual lines are converted to numbers using the parseInt function. Finally, this array is returned as a result.

 const digitize = n => [...'${n}'].map(i => parseInt(i)); 
0
source share

All Articles