JavaScript Number Split into individual digits
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
*/
How do I separate an integer into separate digits in an array in JavaScript?
Why not just do this?
var n = 123456789;
var digits = (""+n).split("");
How to split a number into its digits in Javascript?
var num = 4563;var sum = 0;while(num > 0) { sum += num % 10; num = Math.floor(num / 10);}console.log(sum);
How can I split array of Numbers to individual digits in JavaScript?
You could join the items, split and map numbers.
var array = [ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106], pieces = array.join('').split('').map(Number); console.log(pieces);
How to split numbers in an array into single digits
You could join and get a new array.
const
values = [1, 23, 456, 7890],
result = Array.from(values.join(''), Number);
console.log(result);
Split a number to individual digits in javascript using basic methods
Your error is here:
for (var count = 0; count < number.toString().length; count++)
arr[count] = number % 10;
number = Math.floor(number / 10);
Only the first statement is included in the for loop, the second only runs after the for loop ends. You need braces around both statements so both run on each iteration.
for (var count = 0; count < number.toString().length; count++) {
arr[count] = number % 10;
number = Math.floor(number / 10);
}
But you'll still get the wrong result because you reset the limit for count on each iteration. Set it once at the start.
var count = 0;var arr = [];
function Split(number) { if (Math.floor(number / 10) > 0) { for (var count = 0, countLen = number.toString().length; count < countLen; count++) { arr[count] = number % 10; number = Math.floor(number / 10); } } return arr;}document.write(Split(2345));
Related Topics
How to Define Setter/Getter on Prototype
Generate Unique Number Within Range (0 - X), Keeping a History to Prevent Duplicates
Es6: Conditional & Dynamic Import Statements
How to Implement Prepend and Append with Regular JavaScript
Calling a JSON API with Node.Js
Google Maps API - Getting Closest Points to Zipcode
Sum of Two Numbers with Prompt
What Are the Actual Uses of Es6 Weakmap
Differencebetween & VS @ and = in Angularjs
Add Onclick Event to Newly Added Element in JavaScript
Using Ajax to Read Local Files
When Should I Use ? (Nullish Coalescing) VS || (Logical Or)
How to Do String Replace in JavaScript to Convert '9.61' to '9:61'
Failed to Execute 'Createobjecturl' on 'Url':
Array.Push() Makes All Elements the Same When Pushing an Object