Rotate the elements in an array in JavaScript

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

    I would probably do something like this:

    Array.prototype.rotate = function(n) {
        return this.slice(n, this.length).concat(this.slice(0, n));
    }
    

    Edit    Here’s a mutator version:

    Array.prototype.rotate = function(n) {
        while (this.length && n < 0) n += this.length;
        this.push.apply(this, this.splice(0, n));
        return this;
    }
    
    0 讨论(0)
  • 2020-11-22 11:06

    Here is a very simple way to shift items in an array:

    function rotate(array, stepsToShift) {
    
        for (var i = 0; i < stepsToShift; i++) {
            array.unshift(array.pop());
        }
    
        return array;
    }
    
    0 讨论(0)
  • 2020-11-22 11:07

    When I couldn't find a ready-made snippet to start a list of days with 'today', I did it like this (not quite generic, probably far less refined than the above examples, but did the job):

    //returns 7 day names with today first
    function startday() {
        const days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
        let today = new Date();
        let start = today.getDay(); //gets day number
        if (start == 0) { //if Sunday, days are in order
            return days
        }
        else { //if not Sunday, start days with today
            return days.slice(start).concat(days.slice(0,start))
        }
    }
    

    Thanks to a little refactor by a better programmer than me it's a line or two shorter than my initial attempt, but any further comments on efficiency are welcome.

    0 讨论(0)
  • 2020-11-22 11:08

    Array in JS has below built in method which can be used to rotate an array quite easily and obviously these methods are immutable in nature.

    • push: Inserts the item to end of the array.
    • pop: Removes the item from the end of the array.
    • unshift: Inserts the item to the beginning of the array.
    • shift: Removes the item from the beginning of the array.

    The below solution (ES6) takes two arguments , array needs to be rotated and n , number of times the array should be rotated.

    const rotateArray = (arr, n) => {
      while(arr.length && n--) {
        arr.unshift(arr.pop());
      }
      return arr;
    }
    
    rotateArray(['stack', 'overflow', 'is', 'Awesome'], 2) 
    // ["is", "Awesome", "stack", "overflow"]
    

    It can be added to Array.prototype and can be used all across your application

    Array.prototype.rotate = function(n) {
     while(this.length && n--) {
       this.unshift(this.pop());
     }
     return this;
    }
    [1,2,3,4].rotate(3); //[2, 3, 4, 1]
    
    0 讨论(0)
  • 2020-11-22 11:09

    Using ES6's spread for an immutable example ...

    [...array.slice(1, array.length), array[0]]
    

    and

    [array[array.items.length -1], ...array.slice(0, array.length -1)]
    

    It's probably not the most efficient though but it's concise.

    0 讨论(0)
  • 2020-11-22 11:09
    Follow a simpler approach of running a loop to n numbers and shifting places upto that element.
    
    function arrayRotateOne(arr, n) {
      for (let i = 0; i < n; i++) {
        arr.unshift(arr.pop());
      }
      return arr;
    }
    console.log( arrayRotateOne([1,2,3,4,5,6],2));
    
    
    
    function arrayRotateOne(arr,n) {
      for(let i=0; i<n;i++){
          arr.push(arr.shift());
          console.log('execute',arr)
        }
         return arr;
     }
    

    console.log( arrayRotateOne([1,2,3,4,5,6],2));

    0 讨论(0)
提交回复
热议问题