Rotate array element in JavaScript

Akshay Waingankar
3 min readMay 9, 2022

Rotating array elements to left or right is one of the frequently asked question in technical rounds or you will find this requirement in your coding career. So let's see how we can achieve this with minimum code and effort.

We will use shift(), pop(), push(), unshift() to achieve the solution. Let's understand what are these functions and why we are using those.

  1. shift()

It will remove the first element from an array and return that removed element in the result.

let items_list = [1,2,3,4,5,6,7];
console.log("Original Array", items_list);
let shiftResult = items_list.shift();
console.log("shiftResult", shiftResult);
console.log("New Array", items_list);
shift() output

2. pop()

It will remove the last element from an array and return that removed element in the result.

let items_list = [1,2,3,4,5,6,7];
console.log("Original Array", items_list);
let popResult = items_list.pop();
console.log("popResult", popResult);
console.log("New Array", items_list);
pop() output

3. push()

This function will add a new element at the end of an array

let items_list = [1,2,3,4,5,6,7];
console.log("Original Array", items_list);
items_list.push(100);
console.log("New Array", items_list);
push() output

4. unshift()

This function will add a new element at the beginning of an array

let items_list = [1,2,3,4,5,6,7];
console.log("Original Array", items_list);
items_list.unshift(100);
console.log("New Array", items_list);
unshift() output

Now let's combine all these functions and get into the main purpose.

Rotate element to the left side

We are using shift() to delete the first element and then using push() to insert the same element at the end of an array

let items_list = [1,2,3,4,5,6,7];
console.log("Original Array", items_list);
let shiftResult = items_list.shift();
items_list.push(shiftResult);
console.log("New Array", items_list);
Array element rotates to the left side

Rotate element to the right side

We are using pop() to delete the last element and add the same element at the beginning of an array

let items_list = [1,2,3,4,5,6,7];
console.log("Original Array", items_list);
let popResult = items_list.pop()
items_list.unshift(popResult);
console.log("New Array", items_list);
Array element rotates to the right side

Thats how we can rotate array of an element using shift(), pop(), push() and unshift()function.

I hope you enjoyed reading this and understood the concepts as well. I will try to share more such articles in the coming time. Stay tuned.

Thanks🙂

--

--