JavaScript Number Split into individual digits

var num = 123456;
var digits = num.toString().split('');
var realDigits = digits.map(Number)
console.log(realDigits);

var number = 12354987,
    output = [],
    sNumber = number.toString();

for (var i = 0, len = sNumber.length; i < len; i += 1) {
    output.push(+sNumber.charAt(i));
}

console.log(output);

/* Outputs:
 *
 * [1, 2, 3, 5, 4, 9, 8, 7]
 */ 

UPDATE: Calculating a sum

for (var i = 0, sum = 0; i < output.length; sum += output[i++]);
console.log(sum);

/*
 * Outputs: 39
 */

You can also do it in the "mathematical" way without treating the number as a string:

var num = 278;
var digits = [];
while (num > 0) {
    digits.push(num % 10);
    num = Math.trunc(num / 10);
}
digits.reverse();
console.log(digits);

One upside I can see is that you won't have to run parseInt() on every digit, you're dealing with the actual digits as numeric values.


This is the shortest I've found, though it does return the digits as strings:

let num = 12345;

[...num+''] //["1", "2", "3", "4", "5"]

Or use this to get back integers:

[...num+''].map(n=>+n) //[1, 2, 3, 4, 5]

I will provide a variation on an answer already given so you can see a different approach that preserves the numeric type all along:

var number = 12354987,
    output = [];

while (number) {
    output.push(number % 10);
    number = Math.floor(number/10);
}

console.log(output.reverse().join(',')); // 1,2,3,5,4,9,8,7

I've used a technique such as the above to good effect when converting a number to Roman numerals, which is one of my favorite ways to begin to learn a programming language I'm not familiar with. For instance here is how I devised a way to convert numbers to Roman numerals with Tcl slightly after the turn of the century: http://code.activestate.com/recipes/68379-conversion-to-roman-numerals/

The comparable lines in my Tcl script being:

  while {$arabic} {
    set digit [expr {$arabic%10}]
    set arabic [expr {$arabic/10}]