title: JavaScript sort array by index in a vertical way
body: <p>I have this array:["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]</p>
  
  <p>I get the number of the columns to display it from the server, for this example I chose 3.</p>
  
  <p>So far I have this function that works fine except if my index is equal to the array length something goes wrong in the order and I don't know how to fix it.</p>
  
  <pre><code>var i;
  var j;
  var columns = window.columns; //3 for the example.
  var lettersArray= ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
  var rows = Math.ceil(lettersArray.length/columns);
  </code></pre>
  
  <p>So far I have this:</p>
  
  <pre><code> for (i = 0; i &lt; rows; i++)
              {
                       for (j=0; j &lt; lettersArray.length; j=j+rows)  
                       {
  
                          var index = i+j;
                          if (index&gt;=lettersArray.length)
                          {
                              break;
                          }
                          else
                          {
                            PrintArray(lettersArray, index); 
                          }   
                       }
              }
  </code></pre>
  
  <p>The PrintArray function receive the index and the array after the sorting and it suppose to look like this in the end:</p>
  
  <pre><code>A J S 
  B K T 
  C L U 
  D M V
  E N W
  F O X
  G P Y 
  H Q Z 
  I R
  </code></pre>
  
  <p>But somewhere in the way something goes wrong and it looks like:</p>
  
  <pre><code>A J S 
  B K T 
  C L U 
  D M V
  I N W
  F O X
  G P Y 
  H Q R 
  E Z
  </code></pre>