Languages
[Edit]
EN

JavaScript - convert integer number to array of digits

0 points
Created by:
Zayaan-Rasmussen
543

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:

  1. toString() - converts the number to a string,
  2. from() - creates an array of strings from previously created string,
  3. map() - maps all the elements from an array of strings to Number 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]

 

References

  1. Array.from() - JavaScript | MDN
  2. Number.prototype.toString() - JavaScript | MDN
  3. Array.prototype.map() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join