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?
You can just use the String() method. It coverts to string but you can use them in term of digits.
let numbers = String(val);
console.log(numbers);
First, the integer is converted string & then to array. Using map function, individual strings are converted to numbers with the help of parseInt function. Finally, that array is returned as the result.
const digitize = n => [...`${n}`].map(i => parseInt(i));
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;
}
Another way is by using literals and then spread:
const n = 12345;
const arr = [...`${n}`].map(Number);
console.log(arr);
The solutions proposed work fine in most cases but not with negative numbers.
There is a solution for such cases.
const intToArray = (int) => {
return String(int).match(/-?\d/g).map(Number)
}
console.log(intToArray(312)) // [3, 1, 2]
console.log(intToArray(-312)) // [-3, 1, 2]