title: Sort a 2D Array/Grid/Table of items in Javascript
body: <p>I have an inventory of items in my game and the player will need to have the ability to auto-sort the items based on several criteria being name,quantity and type.</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>// create the Inventory grid
  var InventoryWidth  = 2;
  var InventoryHeight = 4;
  
  var Inventory = new Array(InventoryWidth);
  for (var i = 0; i &lt; InventoryWidth; i++) {
   Inventory[i] = new Array(InventoryHeight);
  }
  
  
  // set the Items &amp; default quantities
  Inventory[0][0] = "Potion";
   Inventory[1][0] = 2;
   
  Inventory[0][1] = "Elixir";
   Inventory[1][1] = 9;
   
  Inventory[0][2] = "Antidote";
   Inventory[1][2] = 5;
  
  Inventory[0][3] = "Ether";
   Inventory[1][3] = 1;
   
  // function for sorting items
  function Sort2D(array2D, byColumn, ascending) {
  
   // sort, seems I am using the wrong sorting function or my approach is wrong here:
    // not sure how to do ASC/DESC as well
   array2D.sort(function(a, b)
   {
    if(a[0] === b[0])
    {
     var x = a[byColumn].toLowerCase(), y = b[byColumn].toLowerCase();
     
     return x &lt; y ? -1 : x &gt; y ? 1 : 0;
    }
    return a[0] - b[0];
   });
  
  }
  
  // sort all rows by first column: "name", setting to 1 should compare and sort the quantities instead
  Sort2D( Inventory, 0, true);
  
  
  // print grid contents
  var output = "";
  for(var i = 0; i &lt; InventoryHeight; i++) {
     
    if (i == 0) {
        output += " | name | own |";
      }
    
   for(var j = 0; j &lt; InventoryWidth; j++) {
    
    if (j == 0) {
     output += "\n"+i+"|";
    }
    
    output+=Inventory[j][i];
    
    if (j &gt;= Inventory[0].length-1) {
     output += "|\n";
    } else {
     output += ", ";
    }
   }
  }
  console.log(output);</code></pre>
  </div>
  </div>
  </p>
  
  <p>However I can't seem to figure out how to sort the grid like a table of items.
  I'd need it to sort the row order by a chosen column and the ability to have it in ASC/DESC order. How would I go about this?</p>