Rotate the elements in an array in JavaScript

后端 未结 30 1213
走了就别回头了
走了就别回头了 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:26

    This function works in both way and works with any number (even with number greater than array length):

    function arrayRotate(arr, count) {
      count -= arr.length * Math.floor(count / arr.length);
      arr.push.apply(arr, arr.splice(0, count));
      return arr;
    }
    

    usage:

    for(let i = -6 ; i <= 6 ; i++) {
      console.log(arrayRotate(["

提交回复
热议问题