15
How to convert a number into an array in JavaScript?
To convert a number into an array, we can use the
from()
method from the global Array
object in JavaScript.// random number
const num = 123456;
// use Array.from() method to convert numbers into an array
// Pass the string version of number "123456" as the first argument
// and the Number constructor as the second argument
const numsArr = Array.from(String(num), Number);
console.log(numsArr); // [1, 2, 3, 4, 5, 6]
Let's consider a number
123456
like this,// random number
const num = 123456;
Now to convert this number into an array, we can first use the
Array.from()
method and pass the stringified version of the number 123456
. To convert the number into a string, we can use the String()
method like this,// random number
const num = 123456;
// use Array.from() method to convert numbers into an array
// Pass the string version of number "123456" as the first argument
const numsArr = Array.from(String(num));
console.log(numsArr); // ["1", "2", "3", "4", "5", "6"]
Now, if we examine the contents of the
numsArr
, we can see that the numbers have been converted to an array. There is only one problem: every element is a string version of the numbers, which is not what we need.To convert the
string
elements into their corresponding number
, we can pass the second argument of the Number
constructor to the Array.from()
method like this,// random number
const num = 123456;
// use Array.from() method to convert numbers into an array
// Pass the string version of number "123456" as the first argument
// and the Number constructor as the second argument
const numsArr = Array.from(String(num), Number);
console.log(numsArr); // [1, 2, 3, 4, 5, 6]
Now if we look into the contents we have the correct numbers as the array elements. Yay π!
See the above code live in JSBin.
That's all π!
15