Table.sort() just sorts randomly when I add a second condition

Basically, I want to sort items by ID, and then by price.
So it will look like:

ID: 1, Price: 250
ID: 1, Price: 500
ID: 1, Price: 750

ID: 2, Price: 250
ID: 2, Price: 500

This is what I have tried:

table.sort(sortedItems, function(a, b)
	return a.ID.Value < b.ID.Value or a.Price.Value < b.Price.Value
end)

But the output is just always random.

I also tried this:

table.sort(sortedItems, function(a, b)
	return a.Price.Value < b.Price.Value
end)

table.sort(sortedItems, function(a, b)
	return a.ID.Value < b.ID.Value
end)

But it was just random as well.
I don’t want to consider making another loop, but if no one has the solution, I’ll be fine with it.

1 Like

Can you show what you’re sorting? You can’t sort a dictionary.

You can’t sort dictionaries, you need to convert the dictionary into an array and then sort that.

image
I’m sorting items in a shop. I added ID Value so it won’t look mixed. I want it to be Cash items first, then Any other value depending on ID.

table.sort(sortedItems, function(a, b)
	if a.ID.Value < b.ID.Value then
		return true
	elseif a.Price.Value < b.Price.Value then
		return true
	end
end)

Make sure you’re using the ipairs() iterator to traverse the data.

Well, I tried that, it’s still random. I don’t understand why. But all cash items have ID 1, and others have different. But cash items could be first anyways.

I tried ipairs() as well.

image

Case closed. This hacky solution saved me from using more loops.

1 Like