How to use mathematical operations In Javascript
In this approach we use a while loop to iterate over the digit of a number. In each iteration of the loop, we use the modulo operator (%) to get the last digit of the number and add it to the beginning of the array using unshift(). We then update the number by dividing it by 10 and taking the floor value using Math.floor(). This process repeats until the number becomes 0.
Example: This example shows the implementation of the above-explained approach.
function numberToArray(number) {
let array = [];
while (number > 0) {
array.unshift(number % 10);
number = Math.floor(number / 10);
}
return array;
}
let number = 12345;
let array = numberToArray(number);
console.log(array);
Output
[ 1, 2, 3, 4, 5 ]
How to convert a number into array in JavaScript ?
In this article, we have been given a number and the task is to convert the given number into an array using JavaScript.
These are the following methods by using these we can solve this problem:
Table of Content
- Using Array.from() Method
- Using map() Method
- Using reduce() function
- Using Lodash _.toArray() Method
- Using mathematical operations
- Using a for loop to iterate through the string representation
Contact Us