Rotate the elements in an array in JavaScript

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

    So many of these answers seem over-complicated and difficult to read. I don't think I saw anyone using splice with concat...

    function rotateCalendar(){
        var cal=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],
        cal=cal.concat(cal.splice(0,new Date().getMonth()));
        console.log(cal);  // return cal;
    }
    

    console.log outputs (*generated in May):

    ["May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb", "Mar", "Apr"]
    

    As for compactness, I can offer a couple of generic one-liner functions (not counting the console.log | return portion). Just feed it the array and the target value in the arguments.

    I combine these functions into one for a four-player card game program where the array is ['N','E','S','W']. I left them separate in case anyone wants to copy/paste for their needs. For my purposes, I use the functions when seeking whose turn is next to play/act during different phases of the game (Pinochle). I haven't bothered testing for speed, so if someone else wants to, feel free to let me know the results.

    *notice, the only difference between functions is the "+1".

    function rotateToFirst(arr,val){  // val is Trump Declarer's seat, first to play
        arr=arr.concat(arr.splice(0,arr.indexOf(val)));
        console.log(arr); // return arr;
    }
    function rotateToLast(arr,val){  // val is Dealer's seat, last to bid
        arr=arr.concat(arr.splice(0,arr.indexOf(val)+1));
        console.log(arr); // return arr;
    }
    

    combination function...

    function rotateArray(arr,val,pos){
        // set pos to 0 if moving val to first position, or 1 for last position
        arr=arr.concat(arr.splice(0,arr.indexOf(val)+pos));
        return arr;
    }
    var adjustedArray=rotateArray(['N','E','S','W'],'S',1);
    

    adjustedArray=

    W,N,E,S
    

提交回复
热议问题