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 right, and a negative n
to the left (-length < n < length
) :
Array.prototype.rotateRight = function( n ) {
this.unshift( this.splice( n, this.length ) );
}
Which can then be used this way:
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
months.rotate( new Date().getMonth() );
My original version above has a flaw, as pointed out by Christoph in the comments bellow, a correct version is (the additional return allows chaining):
Array.prototype.rotateRight = function( n ) {
this.unshift.apply( this, this.splice( n, this.length ) );
return this;
}
Is there a more compact and/or faster solution, possibly in the context of a JavaScript framework? (none of the proposed versions bellow is either more compact or faster)
Is there any JavaScript framework out there with an array rotate built-in? (Still not answered by anyone)
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 🖤🧡💚💙💜