How to use the Array Splice and Push method In Javascript
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 (…).
Example: TypeScript In-Place Array Rotation: Left Rotate by 2 Positions – Demonstrating a function for in-place left rotation of an array by a specified number of positions.
Javascript
function rotateArray(arr, rotateBy) { const n = arr.length; rotateBy %= n; arr.push(...arr.splice(0, rotateBy)); return arr; } 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