title: JavaScript: Rearrange an array in order – largest, smallest, 2nd largest, 2nd smallest, 3rd largest, 3rd smallest,
body: <p>Given an array of integers, where the values should be sorted in the following order:
  if we have an array</p>
  <pre><code>[1, -1, -3, 9, -2, -5, 4, 8,]
  </code></pre>
  <p>we must rearrange it this way: largest number, smallest number, 2nd largest number, 2nd smallest number, ...</p>
  <pre><code>[9, -5, 8, -3,  4, -2, 1, -1 ]
  </code></pre>
  <p>I get the first largest and smallest numbers, but can't figure out how to make it dynamic for all values in the array.</p>
  <p>I know that I must take two variables, say <strong>firstSmallest</strong> and <strong>firstLargest</strong> and point them to the first and last index of the array respectively, run a loop, which I do already in the code below,  and store value into new array by incrementing <strong>firstSmallest</strong> and decrementing <strong>firstLargest</strong>, but couldn't implement into code.</p>
  <pre><code>let unsortedArr = [1, 5, 8 , 7, 6, -1, -5, 4, 9, 5]
  
  let output = [];
  
  function meanderArray(unsorted){
    let sorted = unsorted.sort((a, b) =&gt; a-b);
    let firstSmallest = sorted[0];
    let firstLargest = sorted[unsorted.length-1];
  
    for(let i = 0; i &lt;= sorted.length; i++){
    //I should increment firstSmallest and decrement firstLargest numbers and store in output
    } 
   return output;
  }
  meanderArray(unsortedArr);
  console.log(output);
  </code></pre>