Rotate the elements in an array in JavaScript

后端 未结 30 1587
走了就别回头了
走了就别回头了 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条回答
  •  -上瘾入骨i
    2020-11-22 11:12

    // Example of array to rotate
    let arr = ['E', 'l', 'e', 'p', 'h', 'a', 'n', 't'];
    
    // Getting array length
    let length = arr.length;
    
    // rotation < 0 (move left), rotation > 0 (move right)
    let rotation = 5;
    
    // Slicing array in two parts
    let first  = arr.slice(   (length - rotation) % length, length); //['p', 'h', 'a' ,'n', 't']
    let second = arr.slice(0, (length - rotation) % length); //['E', 'l', 'e']
    
    // Rotated element
    let rotated = [...first, ...second]; // ['p', 'h', 'a' ,'n', 't', 'E', 'l', 'e']
    
    

    In one line of code:

    let rotated = [...arr.slice((length - rotation) % length, length), ...arr.slice(0, (length - rotation) % length)];
    

提交回复
热议问题