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
Returning reverse array of integers using JavaScript
In JavaScript, creating an array of integers in reverse order (from a number down to 1) is a common programming task. This article explores multiple approaches to generate descending arrays efficiently, from basic loops to built-in array methods.
Problem Statement
Create a JavaScript function that generates an array of natural numbers starting from a given number and descending down to 1.
Sample Input:
const num = 5;
Sample Output:
const output = [5, 4, 3, 2, 1];
Method 1: Using For Loop
The most straightforward approach uses a decrementing for loop to build the array:
function generateDescendingArray(num) {
const output = [];
for (let i = num; i >= 1; i--) {
output.push(i);
}
return output;
}
const num = 6;
const result = generateDescendingArray(num);
console.log(result);
[ 6, 5, 4, 3, 2, 1 ]
Method 2: Using Recursion
A recursive approach builds the array by combining the current number with the recursive result:
function reverseArrayRecursive(n) {
if (n === 0) {
return [];
}
return [n].concat(reverseArrayRecursive(n - 1));
}
console.log(reverseArrayRecursive(5));
[ 5, 4, 3, 2, 1 ]
Method 3: Using Array.from()
Array.from() creates an array with a mapping function to generate descending values:
function reverseArrayFrom(n) {
return Array.from({ length: n }, (_, i) => n - i);
}
console.log(reverseArrayFrom(5));
[ 5, 4, 3, 2, 1 ]
Method 4: Using Array.reverse()
This method first creates an ascending array, then reverses it:
function reverseArrayReverse(n) {
let array = Array.from({ length: n }, (_, i) => i + 1);
return array.reverse();
}
console.log(reverseArrayReverse(5));
[ 5, 4, 3, 2, 1 ]
Comparison
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| For Loop | Excellent | High | Low |
| Recursion | Good | Medium | Higher (call stack) |
| Array.from() | Good | High | Low |
| Array.reverse() | Good | High | Medium (creates extra array) |
Conclusion
The for loop approach offers the best performance for generating reverse integer arrays. Array.from() provides excellent readability and is ideal for functional programming styles. Choose the method that best fits your coding style and performance requirements.
