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
You can use push()
, pop()
, shift()
and unshift()
methods:
function arrayRotate(arr, reverse) {
if (reverse) arr.unshift(arr.pop());
else arr.push(arr.shift());
return arr;
}
usage:
arrayRotate(['h','e','l','l','o']); // ['e','l','l','o','h'];
arrayRotate(['h','e','l','l','o'], true); // ['o','h','e','l','l'];
If you need count
argument see my other answer: https://stackoverflow.com/a/33451102