Rotate the elements in an array in JavaScript

后端 未结 30 1207
走了就别回头了
走了就别回头了 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:05

    ** Using Latest version of JS we can build it every easily **

     Array.prototype.rotateLeft = function (n) {
       this.unshift(...this.splice(-(n), n));
        return this
      }
    

    here moves: number of rotations ,a Array that you can pass random number

    let a = [1, 2, 3, 4, 5, 6, 7];
    let moves = 4;
    let output = a.rotateLeft(moves);
    console.log("Result:", output)
    

提交回复
热议问题