Rotating an array to the right means shifting elements towards the end, and elements that go past the last index wrap around to the front.
We can do this using arr.unshift().
1️⃣ Using unshift and pop
pop()removes the last element.unshift()adds one or more elements to the beginning of the array.
function rotateRight(arr, n) {
n = n % arr.length; // handle n > arr.length
for (let i = 0; i < n; i++) {
let last = arr.pop(); // remove last element
arr.unshift(last); // add it to the front
}
return arr;
}
// Example
const array = [1, 2, 3, 4, 5];
console.log(rotateRight(array, 2)); // [4, 5, 1, 2, 3]
Explanation:
- Remove last element using
pop()→5 - Add it to front using
unshift()→[5, 1, 2, 3, 4] - Repeat for
ntimes →[4, 5, 1, 2, 3]
2️⃣ Optimized Version Using Slice (Optional)
function rotateRightOptimized(arr, n) {
n = n % arr.length;
return arr.slice(-n).concat(arr.slice(0, arr.length - n));
}
console.log(rotateRightOptimized([1,2,3,4,5], 2)); // [4,5,1,2,3]
arr.slice(-n)→ lastnelementsarr.slice(0, arr.length - n)→ rest of the elementsconcat()→ combine them in rotated order
⚡ Key Points About unshift
- Adds elements to the start of an array.
- Returns the new length of the array.
- Can be used with
pop()to rotate arrays efficiently in small steps.
In short:
To rotate an array to the right, repeatedly
pop()the last element andunshift()it to the front, or use slicing for an optimized single-step rotation.