Reputation: 98
I have an integer and want to create an array from each of its numbers.
let interget = 345;
//I want create the array [3,4,5]
Is there any easy way to do this using Array.from() or would I need to convert the number to a string first?
Upvotes: 0
Views: 99
Reputation: 5308
Or you can do it like this:
var result = Array.from('345', Number)
console.log(result);
Upvotes: 2
Reputation: 6904
easy way by converting to string
(inputNumber + "").split("").map(char => +char)
basically we split string and convert each character back to number
doing it manually
function getDigits(n) {
const ans = [];
while(n > 0){
let digit = n % 10;
ans.push(digit);
n -= digit;
n /= 10;
}
return ans.reverse();
}
Upvotes: 2