Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
124
rated 0 times [  127] [ 3]  / answers: 1 / hits: 26480  / 11 Years ago, fri, april 19, 2013, 12:00:00

I have this array:



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


I need to shift it to right by say 2 locations, like



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 don't know how to do shift right...


More From » javascript

 Answers
64

Shift to right to N positions == shift to left to array.length - N positions.



So to shift right on 2 positions for you array - just shift it left on 3 positions.



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


[#78786] Thursday, April 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donovantyriqn

Total Points: 271
Total Questions: 98
Total Answers: 113

Location: Saint Vincent and the Grenadines
Member since Sat, Sep 11, 2021
3 Years ago
;