Skip to content Skip to sidebar Skip to footer

Javascript Rotate Array Elements

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

Solution 1:

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(' '));

Solution 2:

you can use swift and push

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

//Testvar players = ['Bob','John','Mack','Malachi'];
rotate( players ,2 )
console.log( players );

Solution 3:

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)
}

Solution 4:

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);
}

Post a Comment for "Javascript Rotate Array Elements"