Rotate Array in JavaScript

A function for rotating arrays to the right or to the left, any number of times.

1. function RotateArr(arr, turns)
2. {
3.    for(var l = arr.length, turns = (Math.abs(turns) >= l && (turns %= l), 
turns < 0 && (turns += l), turns), i, x; turns; turns = (Math.ceil(l / turns) - 1) * turns - l + (l = turns))
4.        for(i = l; i > turns; x = arr[--i], arr[i] = arr[i - turns], arr[i - turns] = x);
5.    return arr;
6. };
7. 
8. RotateArr([4,8,15,16,23,42], 2) // Rotates two to the right
9. RotateArr([4,8,15,16,23,42], -5) // Rotates five to the left

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top