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.
Practical examples
Solution 1
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.
// ONLINE-RUNNER:browser;
const number = 12345;
const digits = Array.from(number.toString()).map(Number);
console.log(digits); // [ 1, 2, 3, 4, 5 ]
Solution 2
In this solution, we create a reusable arrow function that iterates through the number dividing it by 10
in each step.
// ONLINE-RUNNER:browser;
const toArray = (number) => {
if (number < 0) {
number = -number;
}
const array = [];
while (true) {
const step = Math.floor(number / 10);
array.unshift(number - 10 * step);
if (step === 0) {
break;
}
number = step;
}
return array;
};
// Usage example:
const number = 12345;
const digits = toArray(number);
console.log(digits); // [1, 2, 3, 4, 5]
Solution 3 - the most efficient
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.
// ONLINE-RUNNER:browser;
const calculateLength = (number) => {
if (number < 0) {
number = -number;
}
if (number < 2) {
return 1;
}
return Math.ceil(0.43429448190325176 * Math.log(number + 1)); // or just: ceil(log10(number + 1))
};
const toArray = (number) => {
if (number < 0) {
number = -number;
}
const length = calculateLength(number);
const array = new Array(length);
for (let i = length - 1; i > -1; --i) {
const step = Math.floor(number / 10);
array[i] = number - 10 * step;
number = step;
}
return array;
};
// Usage example:
const number = 12345;
const digits = toArray(number);
console.log(digits); // [1, 2, 3, 4, 5]