Psych Half Psych Half - 1 year ago 100
Javascript Question

How to convert an integer into an array of digits

I want to convert an integer, say

, to an array like
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download