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
How to reverse a portion of an array in JavaScript?
We are required to write a JavaScript function that takes in an array, a start index and an end index. The function should reverse the portion of the array between the start index and end index.
For example, if the array is:
const arr = [2, 6, 5, 8, 3, 5, 2, 6, 7];
And the start index and end index are 3, 7 respectively, then the array should be reversed to:
const output = [2, 6, 5, 2, 5, 3, 8, 6, 7];
Using Array Splice Method
This approach extracts the portion to reverse, reverses it, and reinserts it back into the original array:
const arr = [2, 6, 5, 8, 3, 5, 2, 6, 7];
const start = 3, end = 7;
const reverse = arr => {
const { length: l } = arr;
for(let i = 0; i < Math.floor(l/2); i++){
const temp = arr[i];
arr[i] = arr[l-i-1];
arr[l-i-1] = temp;
};
return arr;
};
const reverseBetween = (arr, start, end) => {
const num = Math.min(end - start, arr.length - start);
arr.splice(start, 0, ...reverse(arr.splice(start, num)));
}
reverseBetween(arr, start, end);
console.log(arr);
[ 2, 6, 5, 2, 5, 3, 8, 6, 7 ]
Using In-Place Reversal (Simpler Approach)
A more straightforward method that directly swaps elements within the specified range:
const arr2 = [2, 6, 5, 8, 3, 5, 2, 6, 7];
function reversePortionInPlace(arr, start, end) {
// Ensure end doesn't exceed array length
end = Math.min(end, arr.length - 1);
while (start < end) {
// Swap elements at start and end positions
[arr[start], arr[end]] = [arr[end], arr[start]];
start++;
end--;
}
}
reversePortionInPlace(arr2, 3, 7);
console.log(arr2);
[ 2, 6, 5, 2, 5, 3, 8, 6, 7 ]
Comparison
| Method | Space Complexity | Readability | Performance |
|---|---|---|---|
| Array Splice | O(n) - creates temporary arrays | Complex | Slower due to array operations |
| In-Place Reversal | O(1) - no extra space | Simple | Faster with direct swaps |
Key Points
- Both methods modify the original array
- The in-place method is more efficient in terms of memory and performance
- Always validate that the end index doesn't exceed the array length
- ES6 destructuring assignment makes element swapping cleaner
Conclusion
The in-place reversal method is recommended for its simplicity and efficiency. It directly swaps elements without creating additional arrays, making it both memory-efficient and easier to understand.
