Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I separate an integer into separate digits in an array in JavaScript?

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!

like image 252
magnusbl Avatar asked Mar 28 '12 19:03

magnusbl


People also ask

How do you separate integers into digits?

You can convert a number into String and then you can use toCharArray() or split() method to separate the number into digits.

How do you split values in an array?

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.

Can you split numbers in JS?

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.


2 Answers

Why not just do this?

var n =  123456789; var digits = (""+n).split(""); 
like image 52
Niet the Dark Absol Avatar answered Sep 30 '22 08:09

Niet the Dark Absol


What about:

const n = 123456; Array.from(n.toString()).map(Number); // [1, 2, 3, 4, 5, 6] 
like image 21
Nicolás Fantone Avatar answered Sep 30 '22 10:09

Nicolás Fantone