Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Convert number to a reversed array of digits in JavaScript
Given a non-negative integer, we need to write a function that returns an array containing the digits in reverse order. This is a common programming challenge that demonstrates string manipulation and array operations.
Example
348597 => The correct solution should be [7,9,5,8,4,3]
Method 1: Using String Split and Reverse
The most straightforward approach is to convert the number to a string, split it into individual characters, reverse the array, and convert back to numbers:
const num = 348597;
const reverseArrify = num => {
return String(num).split('').reverse().map(digit => Number(digit));
};
console.log(reverseArrify(num));
console.log(reverseArrify(12345));
console.log(reverseArrify(0));
[ 7, 9, 5, 8, 4, 3 ] [ 5, 4, 3, 2, 1 ] [ 0 ]
Method 2: Using Mathematical Operations
We can also solve this without string conversion by using modulo and division operations:
const reverseArrifyMath = num => {
const result = [];
while (num > 0) {
result.push(num % 10);
num = Math.floor(num / 10);
}
return num === 0 && result.length === 0 ? [0] : result;
};
console.log(reverseArrifyMath(348597));
console.log(reverseArrifyMath(12345));
console.log(reverseArrifyMath(0));
[ 7, 9, 5, 8, 4, 3 ] [ 5, 4, 3, 2, 1 ] [ 0 ]
Method 3: Using Spread Operator
A more concise approach using the spread operator:
const reverseArrifySpread = num => {
return [...String(num)].reverse().map(Number);
};
console.log(reverseArrifySpread(348597));
console.log(reverseArrifySpread(789));
[ 7, 9, 5, 8, 4, 3 ] [ 9, 8, 7 ]
Comparison
| Method | Readability | Performance | Code Length |
|---|---|---|---|
| String Split & Reverse | High | Good | Medium |
| Mathematical Operations | Medium | Best | Long |
| Spread Operator | High | Good | Short |
Key Points
- All methods handle single-digit numbers and zero correctly
- String-based approaches are more readable but involve type conversion
- Mathematical approach avoids string conversion but requires more code
- The spread operator provides the most concise solution
Conclusion
Converting numbers to reversed digit arrays can be achieved through multiple approaches. The string split and reverse method offers the best balance of readability and performance for most use cases.
