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
@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