Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 959
jonnyhitek Avatar asked Oct 16 '11 13:10

jonnyhitek


People also ask

How do I split a number in JavaScript?

To split a number into an array:Convert the number to a string. Call the split() method on the string to get an array of strings. Call the map() method on the array to convert each string to a number.

How do you split a number in node JS?

The split() function is a string function of Node. js which is used to split string into sub-strings. This function returns the output in array form. Parameters: This function accepts single parameter separator which holds the character to split the string.


1 Answers

var num = 123456;  var digits = num.toString().split('');  var realDigits = digits.map(Number)  console.log(realDigits);
like image 68
Brian Glaz Avatar answered Sep 21 '22 03:09

Brian Glaz