EN
JavaScript - animated array rotation
0
points
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);