EN
JavaScript - convert integer number to array of digits
0 points
In this article, we would like to show you how to convert integer number to array of digits in JavaScript.
In this section, we convert the integer number to array of digits using three methods:
toString()
- converts the number to a string,from()
- creates an array of strings from previously created string,map()
- maps all the elements from an array of strings toNumber
type.
xxxxxxxxxx
1
const number = 12345;
2
3
const digits = Array.from(number.toString()).map(Number);
4
5
console.log(digits); // [ 1, 2, 3, 4, 5 ]
In this solution, we create a reusable arrow function that iterates through the number dividing it by 10
in each step.
xxxxxxxxxx
1
const toArray = (number) => {
2
if (number < 0) {
3
number = -number;
4
}
5
const array = [];
6
while (true) {
7
const step = Math.floor(number / 10);
8
array.unshift(number - 10 * step);
9
if (step === 0) {
10
break;
11
}
12
number = step;
13
}
14
return array;
15
};
16
17
18
// Usage example:
19
20
const number = 12345;
21
const digits = toArray(number);
22
23
console.log(digits); // [1, 2, 3, 4, 5]
In this solution we use log10
to calculate the length of a number, then we use this to allocate an array, which makes the approach more efficient.
xxxxxxxxxx
1
const calculateLength = (number) => {
2
if (number < 0) {
3
number = -number;
4
}
5
if (number < 2) {
6
return 1;
7
}
8
return Math.ceil(0.43429448190325176 * Math.log(number + 1)); // or just: ceil(log10(number + 1))
9
};
10
11
const toArray = (number) => {
12
if (number < 0) {
13
number = -number;
14
}
15
const length = calculateLength(number);
16
const array = new Array(length);
17
for (let i = length - 1; i > -1; --i) {
18
const step = Math.floor(number / 10);
19
array[i] = number - 10 * step;
20
number = step;
21
}
22
return array;
23
};
24
25
26
// Usage example:
27
28
const number = 12345;
29
const digits = toArray(number);
30
31
console.log(digits); // [1, 2, 3, 4, 5]