JavaScript Program to Rotate Array Elements
arr.slice(n).concat(arr.slice(0, n)) where n is the number of positions to rotate; this moves the first n elements to the end.Examples
How to Think About It
Algorithm
Code
function rotateArray(arr, n) { const len = arr.length; const rotation = n % len; return arr.slice(rotation).concat(arr.slice(0, rotation)); } const input = [1, 2, 3, 4, 5]; const rotated = rotateArray(input, 2); console.log(rotated);
Dry Run
Let's trace rotating [1, 2, 3, 4, 5] by 2 positions through the code
Calculate length and rotation
len = 5, rotation = 2 % 5 = 2
Split array
arr.slice(2) = [3, 4, 5], arr.slice(0, 2) = [1, 2]
Concatenate parts
[3, 4, 5].concat([1, 2]) = [3, 4, 5, 1, 2]
| Step | Operation | Result |
|---|---|---|
| 1 | Calculate rotation | 2 |
| 2 | Slice from rotation to end | [3, 4, 5] |
| 3 | Slice from start to rotation | [1, 2] |
| 4 | Concatenate slices | [3, 4, 5, 1, 2] |
Why This Works
Step 1: Calculate effective rotation
Using n % arr.length ensures rotation works even if n is larger than the array size.
Step 2: Split the array
We use slice to get two parts: from the rotation index to the end, and from the start to the rotation index.
Step 3: Join the parts
Concatenating these two parts moves the first n elements to the end, completing the rotation.
Alternative Approaches
function rotateArrayLoop(arr, n) { const len = arr.length; const rotation = n % len; for (let i = 0; i < rotation; i++) { const first = arr.shift(); arr.push(first); } return arr; } console.log(rotateArrayLoop([1, 2, 3, 4, 5], 2));
function rotateArrayReverse(arr, n) { const len = arr.length; const rotation = n % len; function reverse(subArr, start, end) { while (start < end) { [subArr[start], subArr[end]] = [subArr[end], subArr[start]]; start++; end--; } } reverse(arr, 0, rotation - 1); reverse(arr, rotation, len - 1); reverse(arr, 0, len - 1); return arr; } const arr = [1, 2, 3, 4, 5]; console.log(rotateArrayReverse(arr, 2));
Complexity: O(n) time, O(n) space
Time Complexity
The main method uses slice and concat, each scanning parts of the array once, so it runs in linear time relative to array size.
Space Complexity
It creates a new array for the rotated result, so it uses extra space proportional to the array size.
Which Approach is Fastest?
The reverse method is fastest and uses O(1) extra space but is more complex; the slice-concat method is simpler but uses extra space.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slice and Concat | O(n) | O(n) | Simplicity and readability |
| Loop Shift | O(n * rotation) | O(1) | Small rotations, in-place modification |
| Reverse Method | O(n) | O(1) | Performance and in-place rotation |
n % arr.length to handle rotations larger than the array size.