DEV Community

loading...
Cover image for How to convert a number into an array in JavaScript?

How to convert a number into an array in JavaScript?

MELVIN GEORGE
Hi, I'm Melvin George, A web developer, and a blogger.
Originally published at melvingeorge.me ・2 min read

Originally posted here!

To convert a number into an array, we can use the from() method from the global Array object in JavaScript.

TL;DR

// 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]
Enter fullscreen mode Exit fullscreen mode

Let's consider a number 123456 like this,

// random number
const num = 123456;
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

NOTE: We are converting the number into a string since string types in JavaScript can be array-like or iterable, which is what the first argument of the Array.from() method expects.

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]
Enter fullscreen mode Exit fullscreen mode

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 😃!

Feel free to share if you found this useful 😃.


Discussion (0)