-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,801
  • 22
  • 38
  • 47
Kishore Jv
  • 127
  • 2
  • 15

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
  • 323,592
  • 20
  • 270
  • 324
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,161
  • 1
  • 24
  • 43