Languages
[Edit]
EN

JavaScript - rotate elements in array

0 points
Created by:
Zoya-Gaines
653

In this article, we would like to show you how to rotate elements in array in JavaScript.

1. Rotate right

In this example, we use the pop() method to extract an element from the end of the array and unshift() to place it at the beginning.

// ONLINE-RUNNER:browser;

const rotateRight = (array) => {
    return array.unshift(array.pop());
};


// Usage example

const array = [1, 2, 3, 4];

rotateRight(array);
console.log(array);  // [4, 1, 2, 3]

rotateRight(array);
console.log(array);  // [3, 4, 1, 2]

rotateRight(array);
console.log(array);  // [2, 3, 4, 1]

rotateRight(array);
console.log(array);  // [1, 2, 3, 4]

2. Rotate left

In this example, we use the shift() method to extract an element from the beginning of the array and push() to place it at the end.

// ONLINE-RUNNER:browser;

const rotateLeft = (array) => {
    return array.push(array.shift());
};


// Usage example

const array = [1, 2, 3, 4];

rotateLeft(array);
console.log(array); // [ 2, 3, 4, 1 ]

rotateLeft(array);
console.log(array); // [ 3, 4, 1, 2 ]

rotateLeft(array);
console.log(array); // [ 4, 1, 2, 3 ]

rotateLeft(array);
console.log(array); // [ 1, 2, 3, 4 ]

 

See also

  1. JavaScript - animated array rotation

References

  1. Array.prototype.pop() - JavaScript | MDN
  2. Array.prototype.unshift() - JavaScript | MDN
  3. Array.prototype.shift() - JavaScript | MDN
  4. Array.prototype.push() - JavaScript | MDN

Alternative titles

  1. JavaScript - array rotation
  2. JavaScript - rotate items in array
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join