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.
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.
xxxxxxxxxx
1
const rotateRight = (array) => {
2
return array.unshift(array.pop());
3
};
4
5
6
// Usage example
7
8
const array = [1, 2, 3, 4];
9
10
rotateRight(array);
11
console.log(array); // [4, 1, 2, 3]
12
13
rotateRight(array);
14
console.log(array); // [3, 4, 1, 2]
15
16
rotateRight(array);
17
console.log(array); // [2, 3, 4, 1]
18
19
rotateRight(array);
20
console.log(array); // [1, 2, 3, 4]
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.
xxxxxxxxxx
1
const rotateLeft = (array) => {
2
return array.push(array.shift());
3
};
4
5
6
// Usage example
7
8
const array = [1, 2, 3, 4];
9
10
rotateLeft(array);
11
console.log(array); // [ 2, 3, 4, 1 ]
12
13
rotateLeft(array);
14
console.log(array); // [ 3, 4, 1, 2 ]
15
16
rotateLeft(array);
17
console.log(array); // [ 4, 1, 2, 3 ]
18
19
rotateLeft(array);
20
console.log(array); // [ 1, 2, 3, 4 ]