Languages
[Edit]
EN

JavaScript - animated array rotation

0 points
Created by:
maryam
1181

In this article, we would like to show you how to create an animated array rotation in JavaScript.

Practical example

In the examples below, we use setInterval() method to call array rotate function every second and display the result in the console.

1. Rotate right

// ONLINE-RUNNER:browser;

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


// Usage example

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

setInterval(() => {
    rotateRight(array);
    console.clear();
    console.log(array);
}, 1000);

2. Rotate left

// ONLINE-RUNNER:browser;

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


// Usage example

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

setInterval(() => {
    rotateLeft(array);
    console.clear();
    console.log(array);
}, 1000);

See also

  1. JavaScript - rotate elements in array

References

  1. setInterval() - Web APIs | MDN
  2. Array.prototype.pop() - JavaScript | MDN
  3. Array.prototype.unshift() - JavaScript | MDN
  4. Array.prototype.shift() - JavaScript | MDN
  5. Array.prototype.push() - JavaScript | MDN
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