How to convert an integer into an array of digits

前端 未结 11 1061
别那么骄傲
别那么骄傲 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:20

    You can just use the String() method. It coverts to string but you can use them in term of digits.

    let numbers = String(val);
    console.log(numbers);
    
    0 讨论(0)
  • 2021-01-30 23:21

    First, the integer is converted string & then to array. Using map function, individual strings are converted to numbers with the help of parseInt function. Finally, that array is returned as the result.

    const digitize = n => [...`${n}`].map(i => parseInt(i));
    
    0 讨论(0)
  • 2021-01-30 23:22

    Here are the two methods I usually use for this. The first method:

    function toArr1(n) {
        "use strict";
        var sum = 0;    
        n = Array.from(String(n), Number); 
           /*even if the type of (n) was a number it will be treated as a string and will 
        convert to an Array*/
        for (i = 0; i < n.length; i += 1) {
            sum += n[i];
        }
        return sum;
    }
    

    The second method:

    function toArr2(n) {
        var sum = 0;
        n = n.toString().split('').map(Number);
        for (i = 0; i < n.length; i += 1) {
            sum += n[i]; 
        }
        return sum;
    }
    
    0 讨论(0)
  • 2021-01-30 23:23

    Another way is by using literals and then spread:

    const n = 12345;
    const arr = [...`${n}`].map(Number);
    console.log(arr);

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

    The solutions proposed work fine in most cases but not with negative numbers.

    There is a solution for such cases.

    const intToArray = (int) => {
      return String(int).match(/-?\d/g).map(Number)
    }
    
    console.log(intToArray(312)) // [3, 1, 2]
    console.log(intToArray(-312)) // [-3, 1, 2]

    0 讨论(0)
提交回复
热议问题