Sorting a dictionary of items

I am currently working on a shop for my game, but i need some objects in a table to be sorted by price.

I currently have a dictionary named items
local Items = {}

In the items dictionary i add the items with a for loop:

for _,v in pairs(FolderName:GetChildren()) do
		Items[v.Name] = {
				["Price"] = v.Price.Value,
				["Asset"] = v,
				["ValueType"] = v.ValueType.Value
		}
end  

But when i do it like this i get a result that looks something like this:

So how do i sort the items in the dictionary

1 Like

I believe table.sort() would work well here:

1 Like

I tried to use the table.sort() but it still gave me the same output

This is what i tested:

table.sort(Items, function(a,b)
return a["Price"] < b["Price"]
end)
1 Like

Maybe you don’t want to sort the items out. table.sort is primarily for sorting arrays. If you have something like a UIListLayout, then you can set the LayoutOrder of your items frames to a certain value: for example, if you’re sorting by price, you can use the price as the LayoutOrder of the frame and it will automatically sort from least to greatest priced item.

5 Likes

That’s what I did and it seems to work just fine. Basically what I’m doing is:

  • Define another table
  • Loop through the dictionary and insert each object into a table using table.insert function
  • Sort the table
  • Loop through the table using numerical for loop
local items = {
    item1 = {
        price = 5
    };
    item2 = {
        price = 2
    };
    item3 = {
        price = 1
    };
    item4 = {
        price = 4
    };
    item5 = {
        price = 3
    };
}

local tab = {}

for i, v in pairs(items) do
    table.insert(tab, v)
end

table.sort(tab, function(a,b) return a.price > b.price end)

for i = 1,#tab do
    print(tab[i].price) --> 5 4 3 2 1
end
3 Likes

How would you automate the making of the table “items”?
I have a folder with items inside containing a price value. It would be easier if I didn’t have to write the “items” table out.