Therefore, I decided to review this without feeling very satisfied with the first answer I gave. I was sure that there would be some relationship between the index numbers when the data was successfully reordered; I found this pattern when adding an iteration number to the last position position.
For our initial array, we will use the following: ['a', 'b', 'c', 'd', 'e'] .
Our starting point is Math.floor( arr.length / 2 ) , which gives us 2 corresponding to c in the array values. This is at iteration 0 . The following instructions detail how we go through an array with an odd number of values:
Position | Direction | Iteration | New Position | Value at Position ----------+-----------+-----------+--------------+------------------- 2 | - | 0 | 2 | c 2 | + | 1 | 3 | d 3 | - | 2 | 1 | b 1 | + | 3 | 4 | e 4 | - | 4 | 0 | a
You will see the template when our iteration is odd, we will add it to our location to find a new position. When the iteration is negative, we subtract it from our position to find a new location.
When working with an array with an even number of values, the rules are inverted. When you have an even number of values, we subtract the odd iterations from the location to get a new position, and even add iterations to our location to find the next value.
To demonstrate how little code is required to execute this sorting logic, the following is a miniature version of the above logic (the above link is more readable):
Implementing the above logic in a more readable way:
// Sort array from inside-out [a,b,c,d,e] -> [c,d,b,e,a] function gut( arr ) { // Resulting array, Counting variable, Number of items, initial Location var out = [], cnt, num = arr.length, loc = Math.floor( num / 2 ); // Cycle through as many times as the array is long for ( cnt = 0; cnt < num; cnt++ ) // Protecting our cnt variable (function(){ // If our array has an odd number of entries if ( num % 2 ) { // If on an odd iteration if ( cnt % 2 ) { // Move location forward loc = loc + (+cnt); } else { // Move location backwards loc = loc + (-cnt); } // Our array has an even number of entries } else { // If on an odd iteration if ( cnt % 2 ) { // Move location backwards loc = loc + (-cnt); } else { // Move location forwards loc = loc + (+cnt); } } // Push val at location to new array out.push( arr[ loc ] ); })() // Return new array return out; }