0

I'm new to Javascript and I'm trying to create a function that rotates the array depending on how many times num is === to. So if num = 2 ["Harry", "Sarah", "Oscar", "Tina"] becomes ["Oscar", "Tina", "Harry", "Sarah"]

Here is my code so far:

var count = 0;

function rotate(arr, num) {
  while (count < num) {
    arr.splice(0,0, "Tina");
    arr.pop();
    count++
  }
  return arr
}

console.log(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2));

For this Line - arr.splice(0,0, "Tina"); I want it to be so that it will bring whatever name is the fourth element to the front of the array, I'm not sure if this is possible? I am suppposed to do this method using splice. Thanks for any help?! :)

Edit: This question is different to other questions. I don't want a full blown solution for rotation, I just want to know if it's possible to splice the fourth element to the beginning?

  • Eerily similar to [Javascript rotating an array using a function with splice?](http://stackoverflow.com/q/29775123/710446) but the mistakes in the code here are distinct from the mistakes in the other question. – apsillers Apr 21 '15 at 16:16
  • *" I just want to know if it's possible to splice the fourth element to the beginning?"* Pretty simple: `arr.unshift(arr.pop())`. – Felix Kling Apr 21 '15 at 16:30

2 Answers2

1

Try shifting the array in a for loop:

function rotate(arr, num){
    for(var i = 0; i < num; i++){
        item = arr[arr.length-1]
        arr.splice(arr.length-1, 1);
        arr.unshift(item)
    }
    return arr
}

alert(JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2)));
alert(JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 1)));
A.J. Uppal
  • 17,608
  • 6
  • 40
  • 70
0

You don't need a loop. First splice the last num elements off the end of the array, then splice them all onto the front.

function rotate(arr, num) {
        var lastN = arr.splice(-num, num);
        [].splice.apply(arr, [0, 0].concat(lastN));
        return arr;
    }
document.getElementById("result").innerHTML = JSON.stringify(rotate(["Harry", "Sarah", "Oscar", "Tina"], 2));
<div id="result"></div>
Barmar
  • 596,455
  • 48
  • 393
  • 495