This website collects cookies to deliver better user experience
How to convert a number into an array in JavaScript?
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.
TL;DR
// random numberconst 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 argumentconst numsArr =Array.from(String(num),Number);console.log(numsArr);// [1, 2, 3, 4, 5, 6]
Let's consider a number 123456 like this,
// random numberconst 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 numberconst num =123456;// use Array.from() method to convert numbers into an array// Pass the string version of number "123456" as the first argumentconst numsArr =Array.from(String(num));console.log(numsArr);// ["1", "2", "3", "4", "5", "6"]
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 numberconst 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 argumentconst 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 🎊!