How to use table.sort on arrays based off a value inside them in arrays

The title at first may be a bit confusing, allow me to explain.

I’m trying to make a shop where my items are sorted by cost from least to greatest,
however, table.sort can only sort numbers inside a table, not sort arrays by values inside them in an array.

Here is an example of the table im trying to sort:

local array = {
["Item2"] = {
["Cost"] = 60,
["Description"] = "No description available."
},
["Item1"] = {
["Cost"] = 20,
["Description"] = "No description available."
},
["Item3"] = {
["Cost"] = 120,
["Description"] = "No description available."
}
}

So my question is, how do I sort my table to have a result like this:

local array = {
["Item1"] = {
["Cost"] = 20,
["Description"] = "No description available."
},
["Item2"] = {
["Cost"] = 60,
["Description"] = "No description available."
},
["Item3"] = {
["Cost"] = 120,
["Description"] = "No description available."
}
}

I would greatly appreciate the answer to this as I’m kind of baffled.

local array = {
["Item2"] = {
["Cost"] = 60,
["Description"] = "No description available."
},
["Item1"] = {
["Cost"] = 20,
["Description"] = "No description available."
},
["Item3"] = {
["Cost"] = 120,
["Description"] = "No description available."
}
}
table.sort(array, function(a, b)
    return a.Cost < b.Cost
end)
5 Likes

You’re not going to be able to use table.sort, because this is a dictionary - not an array.

In order sort your table, you must first change it to be an array, like this :

local array = {
	{
		Name = "Item2",
		Cost = 60,
		Description =  "No description available.",
	},
	{
		Name = "Item1",
		Cost = 20,
		Description =  "No description available.",
	},
	{
		Name = "Item3",
		Cost = 120,
		Description =  "No description available.",
	},
}

Afterwards, you can use the table.sort implementation that @OnceCrowned posted above.

2 Likes

Thank you for this post! While I cannot mark 2 posts as solutions, yours was very important to add to the post I marked as a solution.

Also I just learned the difference between a dictionary and an array because of this :joy: