Saturday, March 30, 2019

javascript - How to splice an element to the start of an array?




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?


Answer



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




No comments:

Post a Comment

plot explanation - Why did Peaches&#39; mom hang on the tree? - Movies &amp; TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...