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?
Here are the two methods I usually use for this. The first method:
function toArr1(n) {
"use strict";
var sum = 0;
n = Array.from(String(n), Number);
/*even if the type of (n) was a number it will be treated as a string and will
convert to an Array*/
for (i = 0; i < n.length; i += 1) {
sum += n[i];
}
return sum;
}
The second method:
function toArr2(n) {
var sum = 0;
n = n.toString().split('').map(Number);
for (i = 0; i < n.length; i += 1) {
sum += n[i];
}
return sum;
}