0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Rotate Array Elements

To rotate an array in JavaScript, use 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

Input[1, 2, 3, 4, 5], n=2
Output[3, 4, 5, 1, 2]
Input[10, 20, 30, 40], n=1
Output[20, 30, 40, 10]
Input[7, 8, 9], n=0
Output[7, 8, 9]
🧠

How to Think About It

To rotate an array, think of moving the first few elements to the end while keeping the order of the rest. You split the array at the rotation point and swap the two parts so the front part goes to the back.
📐

Algorithm

1
Get the input array and the number of positions to rotate, n.
2
Calculate the effective rotation by taking n modulo the array length.
3
Split the array into two parts: from n to end, and from start to n.
4
Concatenate the second part after the first part.
5
Return the new rotated array.
💻

Code

javascript
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);
Output
[3, 4, 5, 1, 2]
🔍

Dry Run

Let's trace rotating [1, 2, 3, 4, 5] by 2 positions through the code

1

Calculate length and rotation

len = 5, rotation = 2 % 5 = 2

2

Split array

arr.slice(2) = [3, 4, 5], arr.slice(0, 2) = [1, 2]

3

Concatenate parts

[3, 4, 5].concat([1, 2]) = [3, 4, 5, 1, 2]

StepOperationResult
1Calculate rotation2
2Slice from rotation to end[3, 4, 5]
3Slice from start to rotation[1, 2]
4Concatenate 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

Using a loop to rotate one by one
javascript
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));
This method modifies the original array but is less efficient for large n because it shifts elements one by one.
Using reverse method
javascript
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));
This in-place method uses reversing parts of the array and is efficient but more complex to understand.

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.

ApproachTimeSpaceBest For
Slice and ConcatO(n)O(n)Simplicity and readability
Loop ShiftO(n * rotation)O(1)Small rotations, in-place modification
Reverse MethodO(n)O(1)Performance and in-place rotation
💡
Use n % arr.length to handle rotations larger than the array size.
⚠️
Forgetting to use modulo causes errors when rotation count exceeds array length.