DEV Community

Sanchithasr
Sanchithasr

Posted on • Edited on

How To Rotate Array Elements using JavaScript Array Methods

As a JavaScript developer, we come across many instances where we need to rotate the array elements to left or right. Many Algorithms need this logic too. So here is the way to rotate the array elements to right and left.

Rotate the Elements to the Left:

We can use array methods push() and shift() to rotate the elements to the left. Let’s see how we could do use these methods.

1) The shift() method removes the first element from an array and returns that removed element.
2) The push() method adds one or more elements to the end of an array and returns the new length of the array.

let starks = ['Rob', 'Jon', 'Sansa', 'Arya', 'Bran']

starks.push(starks.shift())

console.table(starks) 
// expected result: [ 'Jon', 'Sansa', 'Arya', 'Bran', 'Rob' ]
Enter fullscreen mode Exit fullscreen mode

1) The shift() method removes the first element from the array. In our example, The [‘Sansa’] is removed if we do starks.shift().(which should be added to the last).

2) Now the starks.shift() contains [‘Sansa’] and the starks contains [‘Arya’, ‘Bran’, ‘Rob’, ‘Jon’].

3) The push() method adds the one or more elements to the last so the element [‘Sansa’] is added in the last which gives us the array which is rotated to left.


Rotate the Elements to the Right:

We can use array methods unshift() and pop() to rotate the elements to the right. This is how it is gonna work.

1) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
2) The pop() method removes the last element from an array and returns that element.

let starks = ['Rob', 'Jon', 'Sansa', 'Arya', 'Bran']

starks.unshift(starks.pop())

console.log(starks)
// expected result: [ 'Bran', 'Rob', 'Jon', 'Sansa', 'Arya' ]
Enter fullscreen mode Exit fullscreen mode

1) The pop() method removes the last element from an array and returns that element. So we get [‘Jon’] from the starks.pop().

2) The starks.pop() has [‘Jon’] and starks has [‘Sansa’, ‘Arya’, ‘Bran’, ‘Rob’].

3) The unshift() method adds one or more elements to the beginning of an array. We are adding the element we got from stark.pop() ([‘Jon’] is added to the beginning) to the first using unshift().


And that sums up the rotation to left and right using Array methods.

Thank you

Top comments (0)