In my game, there is a inventory system that allows players to automatically sort items based on name, quantity, and type.
// Setting up 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);
}
// Adding Items and 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) {
// Sorting logic goes here:
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];
});
}
// Sorting rows by first column: "name", setting to 1 will compare and sort the quantities instead
Sort2D( Inventory, 0, true);
// Displaying 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 am struggling to understand how to sort the grid like a table of items. I require the ability to sort the rows based on a selected column and also have the option to do it in either ASC or DESC order. How should I approach this?