Open In App

How to rotate array elements by using JavaScript ?

Last Updated : 30 Jun, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

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


Output

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


Output

Elements of array = [GFG_2,GFG_3,GFG_4,GFG_1]


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads