Psych Half Psych Half - 1 month ago 6
Javascript Question

How to convert an integer into an array of digits

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 ;

Answer

I'd go with

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

You can omit the replace if you are sure that n has no decimals.