DEV Community

Cover image for Ways to convert a specified number to an array of digits
Jyoti chaudhary
Jyoti chaudhary

Posted on

1 1

Ways to convert a specified number to an array of digits

Method: 1. Using toString() and for loop
const numberToArray = (number) =>  {
    let str = number.toString();
    let result = [];
    for (let i = 0; i < str.length; i++) {
        result.push(Number(str[i]));
    }
    return result;
}
console.log(numberToArray(12345)); // Output:  [1, 2, 3, 4, 5]

Enter fullscreen mode Exit fullscreen mode
Method: 2.Using toString(), split(), and map()
const numberToArray = (number) =>  {
     return number.toString().split('').map(Number);
}
console.log(numberToArray(123456)); // Output:  [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
Method: 3. Using Math.floor() and a while loop
const numberToArray = (number) =>  {
let result = [];
    while (number > 0) {
        result.unshift(number % 10);  // Get the last digit
        number = Math.floor(number / 10);  // Remove the last digit
    }
    return result;
}
console.log(numberToArray(123456));  // Output:  [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
Method: 4. Using Array.from()
const numberToArray = (number) =>  {
  return Array.from(number.toString(), Number);
}
console.log(numberToArray(123456)); // Output:  [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
Method: 5. Using reduce()
const numberToArray = (number) =>  {
   return number
        .toString()
        .split('')
        .reduce((acc, digit) => {
            acc.push(Number(digit));
            return acc;
        }, []);
}
console.log("Number to array: ", numberToArray(123456));
// Output: Number to array: [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode
Method: 6. Using Recursion
function numberToArray(number) {
    if (number === 0) return [];
    return [...numberToArray(Math.floor(number / 10)), number % 10];
}
let result = numberToArray(123456)
 console.log("Result: ", result); // Output: Result:  [ 1, 2, 3, 4, 5, 6 ]

Enter fullscreen mode Exit fullscreen mode

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more