To convert an integer to an Array of digits, you can use the following approach:
- Convert the integer to a string using the
String()
method. - Split the string into an array containing each digit as a character using the
Array.split()
method. - Convert each character digit of the array into a number using the
Number()
method.
let number = 98315; // Convert number into string let str = String(number); // Split string into a char array const strArr = str.split(''); // Convert each char digit to number const result = strArr.map(digit=>Number(digit)); console.log(result); // Output: [9, 8, 3, 1, 5]
Let’s understand how the above code works.
In the very first step, we converted the number into its equivalent string using the String()
method. The String()
is a built-in function in JavaScript that converts the given value into a string.
String(98315); // "98315"
In the second step, we split the string equivalent of the number into an array using the split()
method.
The split()
method splits the string into an array based on the separator we have passed to it. We passed the empty string(''
) as a separator to the split()
method as we want to split the string at each character.
"98315".split(''); // ["9", "8", "3", "1", "5"]
The array that we got in the second step contains each digit of the number but as a string. Therefore, we have to convert each item of the array into a number using the Number()
method.
To convert each item of the array to a number you can either use a for
loop with the Number()
method or directly use the Array.map()
method.
The map()
method calls a mapping function on each element of the array and returns a new array containing the modified items.
["9", "8", "3", "1", "5"].map(digit=>Number(digit)); // [9, 8, 3, 1, 5]
You can also shorten the above code by avoiding all unnecessary variable declarations and combining the whole code into just a single line.
Something like this:
let number = 98315; // Convert the number into digit array const result = String(number).split('').map(digit=>Number(digit)); console.log(result); // Output: [9, 8, 3, 1, 5]
Method 2: Using the Array.from() method
You can also use the Array.from()
method to convert the integer to an array of digits.
The Array.from()
method takes two parameters and returns a new array.
The first parameter is an iterable object from which we want to create the array and the second is a mapping function which one by one runs on each item of the iterable.
Array.from(iterable, mappingFun);
In our case, the iterable object will be the string that we get by converting the number into a string.
The mapping function will convert each character digit into its equivalent number.
let number = 98315; // Convert the number into digit array const result = Array.from(String(number), (x)=>Number(x)); console.log(result); // Output: [9, 8, 3, 1, 5]
Thanks for reading.