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.
// create the Inventory grid
var InventoryWidth = 2;
var InventoryHeight = 4;
var Inventory = new Array(InventoryWidth);
for (var i = 0; i < InventoryWidth; i++) {
Inventory[i] = new Array(InventoryHeight);
}
// set the Items & 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 < y ? -1 : x > 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 < InventoryHeight; i++) {
if (i == 0) {
output += " | name | own |";
}
for(var j = 0; j < InventoryWidth; j++) {
if (j == 0) {
output += "\n"+i+"|";
}
output+=Inventory[j][i];
if (j >= Inventory[0].length-1) {
output += "|\n";
} else {
output += ", ";
}
}
}
console.log(output);
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?