Let’s say, we have to write a function that takes in a number and returns an array of numbers with elements as the digits of the number but in reverse order. We will convert the number into a string, then split it to get an array of strings of digit, then we will convert the string into numbers, reverse the array and finally return it.
Following is our function that takes in a number to be reversed −
const reversifyNumber = (num) => { const numString = String(num); return numString.split("").map(el => { return +el; }).reverse(); };
Example
const reversifyNumber = (num) => { const numString = String(num); return numString.split("").map(el => { return +el; }).reverse(); }; console.log(reversifyNumber(1245)); console.log(reversifyNumber(123)); console.log(reversifyNumber(5645)); console.log(reversifyNumber(645));
Output
The output in the console will be −
[ 5, 4, 2, 1 ] [ 3, 2, 1 ] [ 5, 4, 6, 5 ] [ 5, 4, 6 ]