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
I am sharing my solution which I am using for rotating on carousel.
It might break when array size is smaller than displayCount, but you could add extra condition to stop rotating when it's small, or concatenating the main array *displayCount times too.
function rotate(arr, moveCount, displayCount) {
const size = arr.length;
// making sure startIndex is between `-size` and `size`
let startIndex = moveCount % size;
if (startIndex < 0) startIndex += size;
return [...arr, ...arr].slice(startIndex, startIndex + displayCount);
}
// move 3 to the right and display 4 items
// rotate([1,2,3,4,5], 3, 4) -> [4,5,1,2]
// move 3 to the left and display 4 items
// rotate([1,2,3,4,5], -3, 4) -> [3,4,5,1]
// move 11 to the right and display 4
// rotate([1,2,3,4,5], 3, 4) -> [2,3,4,5]