How do I sort from smallest to largest

Hi, I have got a little for loop that goes through and gets the price of each item from a table. Any idea how I could sort what it returns from smallest price to biggest?

					for i = num, 0, -1 do
						
						local Asset = MarketPlaceService:GetProductInfo(userTShirts[i])
						
						local assetPrice = Asset.PriceInRobux
						
					end

I’d appreciate any help, thanks. :slight_smile:

2 Likes

okay i think you should try this:

local assets = {2, 1, 3, 5, 4, 6} -- anything in array
local rightArray = {}
local function sort(a)
	for v, i in pairs(a) do
		rightArray[v] = v
	end
	print(table.unpack(rightArray))
end
sort(assets)

Don’t think it’s right solution if you have items with same prices because if you print 11 for example, it will output 7 instead

2 Likes

That code only works with that particular example you provided (assets). As soon as you add values not incremental, it won’t work.

1 Like

yeah ik but we work with numbers(price)

1 Like

The code present at Dictionary Sorting)
should provide you with the solution. You may need to switch the > to a < or vice versa.

1 Like

Ah yes, there will be used table.sort method
example:

table.sort(assets, function(a, b)
	return a < b
end)
print(table.unpack(assets))
1 Like

Thanks, how would I get everything returned from the for loop and put it in a table so that I can then sort it?

for i = num, 0, -1 do
						
						local Asset = MarketPlaceService:GetProductInfo(userTShirts[i])
						
						local assetPrice = Asset.PriceInRobux

					end

Might not work cuz i am not in studio to check any synthax errors or anything

local table1 = {}
for i,v pairs(userTShirts) do
local Asset = MarketPlaceService:GetProductInfo(userTShirts[i])
local assetPrice = Asset.PriceInRobux
local assetName = Asset.Name
table1 = {assetName ,assetPrice}
end
--and sort
1 Like

Thanks, would this still work if this loop ran multiple times, or would it overwrite the previous values in the table?

Basic outline
-- Your table of items with prices
local items = {
    {name = "Item A", price = 10},
    {name = "Item B", price = 5},
    {name = "Item C", price = 15},
    -- Add more items as needed
}

-- Function to compare items by price
local function compareByPrice(item1, item2)
    return item1.price < item2.price
end

-- Sort the items by price
table.sort(items, compareByPrice)

-- Print the sorted items
for _, item in ipairs(items) do
    print(item.name, item.price)
end

2 Likes

Yes it would work it would overwrite the previous values and sort it back

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.