Rotating an array forward by N steps means moving the last N elements to the front while shifting the rest to the right.
1️⃣ Using unshift and pop
function rotateArray(arr, n) {
const len = arr.length;
n = n % len; // handle n > arr.length
for (let i = 0; i < n; i++) {
const last = arr.pop(); // remove last element
arr.unshift(last); // add it to the front
}
return arr;
}
// Example
const arr = [1, 2, 3, 4, 5];
console.log(rotateArray(arr, 2)); // [4, 5, 1, 2, 3]
Explanation:
pop()removes the last elementunshift()adds it to the front- Repeat
ntimes to rotate
2️⃣ Using Slice and Spread Operator (More Efficient)
function rotateArray(arr, n) {
const len = arr.length;
n = n % len; // handle n > arr.length
return [...arr.slice(-n), ...arr.slice(0, len - n)];
}
// Example
const arr = [1, 2, 3, 4, 5];
console.log(rotateArray(arr, 2)); // [4, 5, 1, 2, 3]
Explanation:
arr.slice(-n)→ takes the last N elementsarr.slice(0, len - n)→ takes the first elements- Spread operator combines them → rotated array
⚡ Key Points:
- Always use
n % arr.lengthto handle rotations greater than array length unshift/popmodifies the original arrayslice/spreadreturns a new array without mutation