Skip to content
Advertisement

JavaScript Number Split into individual digits

I am trying to solve a math problem where I take a number e.g. 45, or 111 and then split the number into separate digits e.g. 4 5 or 1 1 1. I will then save each number to a var to run a method on. Does anyone know how to split a number into individual digitals?

For example I have a loop that runs on an array :

for (var i = 0; i < range.length; i++) {
  var n = range[i];
}

For each number, I would like to split its digits and add them together?

Advertisement

Answer

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
 */
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement