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
Partially reversing an array - JavaScript
Suppose, we have an array of literals like this:
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
console.log("Original array:", arr);
Original array: [3, 5, 5, 2, 23, 4, 7, 8, 8, 9]
We are required to write a JavaScript function that takes in such an array and a number, say n (n must be less than or equal to the length of array). And the function should reverse the first n elements of the array within.
For example, if for this array, the number is 4, then the first 4 elements [3, 5, 5, 2] should be reversed to [2, 5, 5, 3], while the remaining elements stay in their original positions.
Example Implementation
Let us write the code for this function:
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const partialReverse = (arr = [], num = 0) => {
const partialArr = arr.slice(0, num);
partialArr.reverse();
arr.splice(0, num, ...partialArr);
};
console.log("Before partial reverse:", arr);
partialReverse(arr, 5);
console.log("After reversing first 5 elements:", arr);
Before partial reverse: [3, 5, 5, 2, 23, 4, 7, 8, 8, 9] After reversing first 5 elements: [23, 2, 5, 5, 3, 4, 7, 8, 8, 9]
How It Works
The function works in three steps:
-
Extract:
arr.slice(0, num)creates a copy of the first n elements -
Reverse:
partialArr.reverse()reverses the extracted portion -
Replace:
arr.splice(0, num, ...partialArr)replaces the original first n elements with the reversed ones
Alternative Approach Using In-Place Swapping
Here's a more memory-efficient approach that reverses elements in-place:
const partialReverseInPlace = (arr, num) => {
for (let i = 0; i
Before: [3, 5, 5, 2, 23, 4, 7, 8, 8, 9]
After reversing first 4 elements: [2, 5, 5, 3, 23, 4, 7, 8, 8, 9]
Comparison
| Method | Memory Usage | Time Complexity | Space Complexity |
|---|---|---|---|
| Slice & Splice | Creates temporary array | O(n) | O(n) |
| In-place Swapping | No extra array needed | O(n/2) | O(1) |
Conclusion
Both approaches successfully reverse the first n elements of an array. The slice & splice method is more readable, while the in-place swapping approach is more memory-efficient for large arrays.
