Rotating an array - JavaScript

In JavaScript, rotating an array means moving elements from one position to another by a specified number of steps. This operation is useful for circular data structures and algorithmic problems.

For example, if we have an array [12, 6, 43, 5, 7, 2, 5] and rotate it by 3 positions to the left, the result would be [5, 7, 2, 5, 12, 6, 43].

Method 1: Using Array Prototype Extension

We can extend the Array prototype to add a rotation method:

// Helper function to rotate by one position
const rotateByOne = arr => {
    for(let i = 0; i = l) {
        return;
    }
    for(let i = 0; i 

[
  3, 4, 5, 6,
  7, 1, 2
]

Method 2: Using Slice and Spread Operator

A more efficient approach using array methods without modifying the prototype:

function rotateArray(arr, n) {
    const len = arr.length;
    // Handle cases where n > array length
    n = n % len;
    
    // Left rotation: take elements from index n and append first n elements
    return [...arr.slice(n), ...arr.slice(0, n)];
}

const originalArray = [12, 6, 43, 5, 7, 2, 5];
const rotated = rotateArray(originalArray, 3);

console.log("Original:", originalArray);
console.log("Rotated by 3:", rotated);
Original: [12, 6, 43, 5, 7, 2, 5]
Rotated by 3: [5, 7, 2, 5, 12, 6, 43]

Method 3: Right Rotation

To rotate elements to the right instead of left:

function rotateRight(arr, n) {
    const len = arr.length;
    n = n % len;
    
    // Right rotation: take last n elements and prepend them
    return [...arr.slice(-n), ...arr.slice(0, -n)];
}

const numbers = [1, 2, 3, 4, 5];
const rightRotated = rotateRight(numbers, 2);

console.log("Original:", numbers);
console.log("Right rotated by 2:", rightRotated);
Original: [1, 2, 3, 4, 5]
Right rotated by 2: [4, 5, 1, 2, 3]

Comparison

Method Time Complexity Space Complexity Mutates Original
Prototype Extension O(n²) O(1) Yes
Slice & Spread O(n) O(n) No
Right Rotation O(n) O(n) No

Conclusion

The slice and spread method is most efficient and doesn't modify the original array. Use prototype extension only when you need in-place rotation and don't mind slower performance.

Updated on: 2026-03-15T23:18:59+05:30

608 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements