-2

I have an array,

 var myArray = [ 1,2,3,4,5 ] 

and variable count,

var count = 5

Pseudocode :

   if count = 1, output myArray = [5,1,2,3,4]  
   if count = 2, then myArray = [ 4,5,1,2,3] 

and so on ..

How can I achieve this without using loops ?

Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
Kishore Jv
  • 159
  • 5
  • 17

2 Answers2

5

You could slice with a negative index from the end the array for the last part and the first part and concat a new array.

function move(array, i) {
    return array.slice(-i).concat(array.slice(0, -i));
}

var array = [1, 2, 3, 4, 5];

console.log(move(array, 1)); // [5, 1, 2, 3, 4].
console.log(move(array, 2)); // [4, 5, 1, 2, 3] 
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

Use pop for removing last item of the array and unshift for adding it at the beginning of the arrray then

const count = 2;
const myArray = [ 1,2,3,4,5 ];
for (let i = 0; i < count; i++) {
  myArray.unshift(myArray.pop());
}
console.log(myArray);
quirimmo
  • 9,800
  • 3
  • 30
  • 45