Rotate the elements in an array in JavaScript

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

    I am coming late but I have a brick to add to these good answers. I was asked to code such a function and I first did:

    Array.prototype.rotate = function(n)
    {
        for (var i = 0; i < n; i++)
        {
            this.push(this.shift());
        }
        return this;
    }
    

    But it appeared to be less efficient than following when n is big:

    Array.prototype.rotate = function(n)
    {
        var l = this.length;// Caching array length before map loop.
    
        return this.map(function(num, index) {
            return this[(index + n) % l]
        });
    }
    

提交回复
热议问题