This is my code so far:
var n = 123456789; var d = n.toString().length; var digits = []; var squaredDigits = []; for (i = d; i >= 1; i--) { var j = k / 10; var r = (n % k / j) - 0.5; var k = Math.pow(10, i); var result = r.toFixed(); digits.push(result); } console.log(digits);
But when I run my code I get this: [9, 1, 2, 3, 4, 5, 6, 7, 8]
If anyone can see the problem or find a better solution I would very much appreciate it!
You can convert a number into String and then you can use toCharArray() or split() method to separate the number into digits.
The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.
JavaScript split method can be used to split number into array. But split method only splits string, so first you need to convert Number to String. Then you can use the split method with a combination of map method to transform each letter to Number.
Why not just do this?
var n = 123456789; var digits = (""+n).split("");
What about:
const n = 123456; Array.from(n.toString()).map(Number); // [1, 2, 3, 4, 5, 6]
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