Rotate the elements in an array in JavaScript

后端 未结 30 1248
走了就别回头了
走了就别回头了 2020-11-22 10:55

I was wondering what was the most efficient way to rotate a JavaScript array.

I came up with this solution, where a positive n rotates the array to the

30条回答
  •  囚心锁ツ
    2020-11-22 11:02

    Using for loop. Here are the steps

    1. Store first element of array as temp variable.
    2. Then swap from left to right.
    3. Then assign temp variable to last element of array.
    4. Repeat these steps for number of rotations.

    function rotateLeft(arr, rotations) {
        let len = arr.length;
        for(let i=0; i ", output);

提交回复
热议问题