2

Hello, everybody, I have this task: I have an array [4,7,3,6,9] and I have to make an array like this:

[4,7,3,6,9]
[9,4,7,3,6]
[6,9,4,7,3]
[3,6,9,4,7]
[7,3,6,9,4]

I have to make a program where array is rotating even if I add a new item to an array it should change accordingly. I am total newbie at JS, 1 week or so, here is my current try:

var numbers = [4, 7, 3, 6, 9];
console.log(numbers);
numbers[0] = 9; numbers[1] = 4; numbers[2] = 7; numbers[3] = 3; numbers[4] = 6;
console.log(numbers);
numbers[0] = 6; numbers[1] = 9; numbers[2] = 4; numbers[3] = 7; numbers[4] = 3;
console.log(numbers);
numbers[0] = 3; numbers[1] = 6; numbers[2] = 9; numbers[3] = 4; numbers[4] = 7;
console.log(numbers);
numbers[0] = 7; numbers[1] = 3; numbers[2] = 6; numbers[3] = 9; numbers[4] = 4;
console.log(numbers);

Also in my mind I have .push, .splice, etc. I dont know why but i really feel that javascript is not for my brain, haha :D

4 Answers4

6

You could pop the value and unshift it.

var array = [4, 7, 3, 6, 9],
    i = array.length;

while (i--) {
    console.log(array.join(' '));
    array.unshift(array.pop());
}
console.log(array.join(' '));
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
2

you can use swift and push

function rotate( array , times ){
while( times-- ){
var temp = array.shift();
 array.push( temp )
 }
}

//Test
var players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );
Aravind
  • 21
  • 3
0

You can simply use splice in conjunction with pop:

var arr = [4,7,3,6,9];
for(var i=0; i<arr.length-1; i++){
  arr.splice(0, 0, arr.pop())
  console.log(arr)
}
Ankit Agarwal
  • 28,439
  • 5
  • 29
  • 55
0

This is my solution:

var numbers = [4, 7, 3, 6, 9];

for(var i = 0; i < numbers.length; i++) {
    console.log(numbers);
    var lastElement = numbers.pop();
    numbers = [lastElement].concat(numbers);
}