Reverse Using Iterative Approach with Array Splicing
In this approach, we iteratively slice the input array into sub-arrays of the given size and reverse each sub-array. We splice the reversed sub-array back into the original array at the same position.
Example:
function reverseSubArrays(arr, k) {
for (let i = 0; i < arr.length; i += k) {
const subArray = arr.slice(i, i + k); // Extract sub-array of size k
const reversedSubArray = subArray.reverse(); // Reverse the sub-array
arr.splice(i, k, ...reversedSubArray); // Replace the original sub-array with the reversed sub-array
}
return arr;
}
// Example usage:
const arr1 = [1, 2, 3, 4, 5, 6];
const k1 = 2;
console.log(reverseSubArrays(arr1, k1)); // Output: [2, 1, 4, 3, 6, 5]
const arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const k2 = 3;
console.log(reverseSubArrays(arr2, k2)); // Output: [3, 2, 1, 6, 5, 4, 9, 8, 7]
Output
[ 2, 1, 4, 3, 6, 5 ] [ 3, 2, 1, 6, 5, 4, 9, 8, 7 ]
Reverse an Array in Groups of Given Size in JavaScript
In this article, we are going to reverse a sub-array of a given size. We will be provided with an array and a random size for the sub-array to be reversed. There exist different variations of this problem.
These are the following variations of reversing the array in groups of a given size:
Table of Content
- Reverse the alternate groups
- Reverse at a given distance
- Reverse by doubling the group size
- Method 4: Reverse Using Iterative Approach with Array Splicing
- Reverse Sub-arrays Using a Deque