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?
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.
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.
var num = 123456;  var digits = num.toString().split('');  var realDigits = digits.map(Number)  console.log(realDigits);  If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With