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); |
[ 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