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
This function is a little faster than the accepted answer for small arrays but MUCH faster for large arrays. This function also allows for an arbitrary number of rotations greater than the length of the array, which is a limitation of the original function.
Lastly, the accepted answer rotates the opposite direction as described.
const rotateForEach = (a, n) => {
const l = a.length;
a.slice(0, -n % l).forEach(item => a.push( item ));
return a.splice(n % l > 0 ? (-n % l) : l + (-n % l));
}
And the functional equivalent (which seems to also have some performance benefits):
const rotateReduce = (arr, n) => {
const l = arr.length;
return arr.slice(0, -n % l).reduce((a,b) => {
a.push( b );
return a;
}, arr).splice(n % l> 0 ? l + (-n % l) : -n % l);
};
You can check out the performance breakdown here.