How to Create an Array from an Integer in JavaScript?

Estimated read time 1 min read

To create an array from an integer in JavaScript, you can follow the steps below:

  1. Convert the integer to a string using the toString() method.
  2. Split the string into an array of individual characters using the split() method.
  3. Map over the array of characters and convert each character back to an integer using the parseInt() method.

Here’s an example code snippet that demonstrates these steps:

const num = 12345;
const arr = num.toString().split('').map(Number);
console.log(arr); // [1, 2, 3, 4, 5]

In this code, the num variable holds the integer value 12345. The toString() method is used to convert this integer to a string, which results in the string value '12345'. The split('') method is used to split this string into an array of individual characters, resulting in the array ['1', '2', '3', '4', '5']. Finally, the map(Number) method is used to map over this array of characters and convert each character to an integer, resulting in the final array [1, 2, 3, 4, 5].

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply