0
\$\begingroup\$

I have an array that I am shifting by a certain number of spaces. I am wondering if there is an better way to do the shift with less touches. Here is my code

function rotate_array(array, shift){

    if(array.length -1 <= shift){
        shift %= array.length;
    }
    for(var i =0; i < shift; i++){
        var first = array[0];
        for(var j =0; j < array.length -1 ;j++){
            array[j] = array[j+1]
        }
        array[array.length - 1]  = first
    }
}

 var array = [4,2,1,3,5];
 rotate_array(array, 22);

  for(var i =0; i < array.length; i++){
    console.log(array[i])
 };
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can just use concat and splice..

shift %= array.length;
array = array.concat(array.splice(0,shift));

Or if you want the same array referance you can shift and push

for(i = 0; i < shift; i ++){
   var item = array.shift();
   array.push(item);
}

or shorten to

while((shift--) > 0){
   array.push(array.shift());
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.