Let's get an array of digits of a number. Let the following number be given:
let num = 12345;
Trying to expand a number in
terms of spread
will
result in an error, since
numbers are not iterable:
let num = 12345;
let arr = [...num]; // an error
console.log(arr);
To solve the problem, we convert the number to a string:
let num = 12345;
let arr = [...String(num)];
console.log(arr); // ['1', '2', '3', '4', '5']
We, however, have an array of
strings, not numbers. Let's
fix the problem with a trick
using the
map
method:
let num = 12345;
let arr = [...String(num)].map(Number);
console.log(arr); // [1, 2, 3, 4, 5]
Given a number. Find the sum of its digits.