EN
JavaScript - rotate elements in array
0
points
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 ]