Reputation: 152
I have javascript array that looks like this
var myArr = [1,2,3,4,5,6,7,8,9];
And I have a setInterval function on every second. And each time function is triggered I need to reorder the array to looks like this [2,3,4,5,6,7,8,9,1] and next time [3,4,5,6,7,8,9,1,2]... Whats the best way to do that.
Upvotes: 0
Views: 344
Reputation: 72857
It's pretty simple: Use a combination of shift
and push
:
var myArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(myArr.join());
var myInterval = setInterval(
function (){
myArr.push(myArr.shift());
console.log(myArr.join());
},
1000
);
setInterval()
runs the supplied function every x milliseconds (1000
, in this case),
shift()
removes the first element from the array it's called on, and returns it,
push()
adds the supplied parameter to the end of the array it's called on.
You can reverse the direction using unshift
and pop
:
var myArr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(myArr.join());
var myInterval = setInterval(
function (){
myArr.unshift(myArr.pop());
console.log(myArr.join());
},
1000
);
Upvotes: 9