Rotate the elements in an array in JavaScript

后端 未结 30 1789
走了就别回头了
走了就别回头了 2020-11-22 10:55

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

30条回答
  •  感动是毒
    2020-11-22 11:23

    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]
    

提交回复
热议问题