Rotate the elements in an array in JavaScript

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

    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.

提交回复
热议问题