How to use Array Reversal In Javascript

This approach involves three steps first reversing the first part of the array, reversing the second part, and then reversing the whole array. This method needs a helper function reverse() to reverse elements within specified ranges and allow us to perform array rotation efficiently.

Example: TypeScript Array Rotation: Left Rotate by 2 Positions – Utilizing Reversal Algorithm – Demonstrating an efficient in-place left rotation algorithm for arrays using reversal.

Javascript




function rotateArray(arr, rotateBy) {
    const n = arr.length;
    rotateBy %= n;
 
    reverse(arr, 0, rotateBy - 1);
    reverse(arr, rotateBy, n - 1);
    reverse(arr, 0, n - 1);
 
    return arr;
}
 
function reverse(arr, start, end) {
    while (start < end) {
        const temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}
 
const originalArray = [1, 2, 3, 4, 5];
const rotatedArray = rotateArray(originalArray, 2);
console.log(rotatedArray);


Output

[ 3, 4, 5, 1, 2 ]


JavaScript Program for array rotation

Array rotation in JavaScript involves shifting elements within an array to the left or right by a specified number of positions.

There are several approaches to rotate an array in JavaScript which are as follows:

Table of Content

  • Using Array Slice and Concatenation Method
  • Using Array Splice and Push method
  • Using Array Reversal

Similar Reads

Using Array Slice and Concatenation Method

This approach involves slicing the array into two parts based on the rotation index and then concatenating them in the desired order. This method first calculates the rotation index, then slices the array accordingly, and concatenates the parts in the rotated order....

Using the Array Splice and Push method

...

Using Array Reversal

This approach involves using the splice() method to remove elements from the beginning of the array and then push them to the end. Here, we first remove the elements to be rotated from the beginning of the array using splice() and then push them to the end using the spread operator (…)....

Contact Us