Fastest way to move first element to the end of an Array

arrays, element, javascript

Solution

Use the shift() and push() functions:

var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.shift());  // results in [1, 2, 3, 4, 5, 6, 7, 8] 

Example:

var ary = [8,1,2,3,4,5,6,7];

console.log("Before: " + ary);

ary.push(ary.shift());  // results in [1, 2, 3, 4, 5, 6, 7, 8] 

console.log("After: " + ary);

Problem

I'm wondering what is the fastest way in JavaScript to move an element from the beginning of an `Array` to the end. For example if we have `[8,1,2,3,4,5,6,7]` And we want: `[1,2,3,4,5,6,7,8]` I want to move the first element to the end. I was thinking about switching element 0 with element 1, after that switching element 1 with element 2 and so on until the 8 is at the and (basically how bubblesort works). I was wondering if there is a faster way to bring the first element to the end. I will be using small Arrays (around 10 elements), and I want to avoid `shift()` since it's pretty slow. This is what I have now on chrome it's 45% faster than normal shift+push: http://jsperf.com/shift-myfunc The arrays will have objects in them for a game.

Original source