Pan array right in javascript

I have this array:

var arr1 = ['a1', 'a2', 'a3', 'a4', 'a5']; 

I need to move it to the right, say, in two places, for example

 arr1 = ['a4', 'a5', 'a1', 'a2', 'a3']; 

This works for left shift:

 arr1 = arr1.concat(arr1.splice(0,2)); // shift left by 2 

I get:

 arr1 = ['a3', 'a4', 'a5', 'a1', 'a2']; 

But I do not know how to move correctly ...

+7
source share
3 answers

Move right to N position == move left to array.length - N positions.

So, to shift to the right by 2 positions for your array - just shift it by 3 positions.

There is no reason to implement another function as soon as you already have it. Plus solutions with shift/unshift/pop in a loop are unlikely to be as efficient as splice + concat

+15
source

You can use .pop() to get the last element and .unshift() to put it in front:

 function shiftArrayToRight(arr, places) { for (var i = 0; i < places; i++) { arr.unshift(arr.pop()); } } 
+8
source

Using .concat() , you create a new array and replace the old one. The problem is that if you have other array references, they will not be updated, so they will still save the unmoved version.

To make the right shift and actually modify the existing array, you can do this:

 arr1.unshift.apply(arr1, arr1.splice(3,2)); 

The unshift() method is variable, and .apply allows .apply to pass multiple arguments stored in a collection similar to an array.

So .splice() mutates the array, deleting the last two and returning them, and .unshift() mutates the array, adding those that return .splice() to the beginning.


The left shift will be rewritten similarly to the right shift, since .push() also variable:

 arr1.push.apply(arr1, arr1.splice(0,2)); 
+5
source

All Articles