Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
9
rated 0 times [  10] [ 1]  / answers: 1 / hits: 173263  / 11 Years ago, fri, october 4, 2013, 12:00:00

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;

More From » javascript

 Answers
44

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.


[#75222] Thursday, October 3, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
;