## DEV Community π©βπ»π¨βπ» is a community of 963,274 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Sanchithasr

Posted on • Updated 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' ]

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' ]

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