Given an array containing some array elements and the task is to perform the rotation of the array with the help of JavaScript.
There are two approaches that are discussed below:
- Using Array unshift() and pop() Methods
- Using Array push() and shift() Methods
Method 1: Using Array unshift() and pop() Methods
We can use the Array unshift() method and Array pop() method to first pop the last element of the array and then insert it at the beginning of the array.
Example: This example rotates the array elements using the above approach.
Javascript
let Arr = [ 'GFG_1' , 'GFG_2' , 'GFG_3' , 'GFG_4' ]; function arrayRotate(arr) { arr.unshift(arr.pop()); return arr; } function myGFG() { let rotateArr = arrayRotate(Arr); console.log( "Elements of array = [" + rotateArr + "]" ); } myGFG(); |
Elements of array = [GFG_4,GFG_1,GFG_2,GFG_3]
Method 2: Using Array push() and shift() Methods
We can use the Array push() method and Array shift() method to shift the first element and then insert it at the end.
Example: This example rotates the array elements using the above approach
Javascript
let Arr = [ 'GFG_1' , 'GFG_2' , 'GFG_3' , 'GFG_4' ]; function arrayRotate(arr) { arr.push(arr.shift()); return arr; } function myGFG() { let rotateArr = arrayRotate(Arr); console.log( "Elements of array = [" + rotateArr + "]" ); } myGFG(); |
Elements of array = [GFG_2,GFG_3,GFG_4,GFG_1]