Fastest way to move first element to the end of an Array
var ary = [8,1,2,3,4,5,6,7];ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
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);
var a = ["a","b","c"];var b = a.shift();a.push(b);
or
var b = a.shift();a[a.length] = b;
Edit Based on updated question
What is going to be the fastest? Really depends on content of the array and what browser/version!
Now what are the ways to remove the first index?
shift()
splice()
slice()
Now what are the ways to add to the last index?
push()
array[array.length]
concat()
-- not even going to try
Other ways
- for loop - make new array [going to be horrible on large arrays]
JSPerf:
http://jsperf.com/test-swapping-of-first-to-last
What is really the fastest?
What is the fastest really depends on what you are doing with the array. If you are just using the first index, it will be fastest just to make your code read an index and not shift the values. If you are using all the indexes, than just loop and through and when you get to the end start back at zero. Basic counters.
And here is a sweet ES6 version
let arr = [1,2,3,4,5,6]const [first, ...rest] = arr;arr = [...rest,first]