How to convert an integer into an array of digits

前端 未结 11 1060
别那么骄傲
别那么骄傲 2021-01-30 23:07

I want to convert an integer, say 12345, to an array like [1,2,3,4,5].

I have tried the below code, but is there a better way to do this?

相关标签:
11条回答
  • 2021-01-30 23:08

    Runnable snippet:

    const n = 12345;
    let toIntArray = (n) => ([...n + ""].map(Number));
    console.log(toIntArray(n));

    0 讨论(0)
  • 2021-01-30 23:10

    I'd go with

    var arr = n.toString(10).replace(/\D/g, '0').split('').map(Number);
    

    You can omit the replace if you are sure that n has no decimals.

    0 讨论(0)
  • 2021-01-30 23:13

    **** 2019 Answer ****

    This single line will do the trick:

    Array.from(String(12345), Number);
    

    Example

    const numToSeparate = 12345;
    
    const arrayOfDigits = Array.from(String(numToSeparate), Number);
    
    console.log(arrayOfDigits);   //[1,2,3,4,5]

    Explanation

    1- String(numToSeparate) will convert the number 12345 into a string, returning '12345'

    2- The Array.from() method creates a new Array instance from an array-like or iterable object, the string '12345' is an iterable object, so it will create an Array from it.

    3- But, in the process of automatically creating this new array, the Array.from() method will first pass any iterable element (every character in this case eg: '1', '2') to the function we set to him as a second parameter, which is the Number function in this case

    4- The Number function will take any string character and will convert it into a number eg: Number('1'); will return 1.

    5- These numbers will be added one by one to a new array and finally this array of numbers will be returned.

    Summary

    The code line Array.from(String(numToSeparate), Number); will convert the number into a string, take each character of that string, convert it into a number and put in a new array. Finally, this new array of numbers will be returned.

    0 讨论(0)
  • 2021-01-30 23:15
    var n = 12345;
    var arr = ('' + n).split('').map(function(digit)  {return +digit;});
    

    The map function, though, is only supported by recent browsers.

    0 讨论(0)
  • 2021-01-30 23:15

    I have fist convert the number to a string and then used Array.from() to convert the string to an array.

    let dataArray = Array.from(value.toString());
    
    0 讨论(0)
  • 2021-01-30 23:19

    I'd do this, to avoid using strings when you don't need them:

    var n = 12345;
    var arr = [];
    while(n>0){arr.unshift(n%10);n=n/10|0;}
    
    0 讨论(0)
提交回复
热议问题