Monday, November 18, 2024
Google search engine
HomeLanguagesJavascriptHow to rotate array elements by using JavaScript ?

How to rotate array elements by using JavaScript ?

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]
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments