Rotate the elements in an array in JavaScript

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

    @Christoph, you've done a clean code, but 60% slowest than this one i found. Look at the result on jsPerf : http://jsperf.com/js-rotate-array/2 [Edit] OK now there is more browsers an that not obvious witch methods the best

    var rotateArray = function(a, inc) {
        for (var l = a.length, inc = (Math.abs(inc) >= l && (inc %= l), inc < 0 && (inc += l), inc), i, x; inc; inc = (Math.ceil(l / inc) - 1) * inc - l + (l = inc))
        for (i = l; i > inc; x = a[--i], a[i] = a[i - inc], a[i - inc] = x);
        return a;
    };
    
    var array = ['a','b','c','d','e','f','g','h','i'];
    
    console.log(array);
    console.log(rotateArray(array.slice(), -1)); // Clone array with slice() to keep original
    

提交回复
热议问题