How to sort table using 2 values in the order

Im trying to sort my inventory with rarity and type of items using table.

local invToSort = {{"i1", 3, 5},{"w1", 1, 1},{"e1", 4, 3},{"a2", 2, 3},{"w2",1, 3},{"i2", 3, 1},{"a1", 2, 4}}
--format: {itemTag, Type, Rarity}

table.sort(invToSort, function(valueA, valueB)
	return valueA.Rarity > valueB.Rarity
end)
		
table.sort(invToSort, function(valueA, valueB)
	return valueA.Type < valueB.Type 
end)

what I got is some item don’t order by rarity.
But the type is fine

Thank. you for helping :grinning:

value A and value B doesnt have Rarity or even Type in it

local invToSort = {{"i1", 3, 5},{"w1", 1, 1},{"e1", 4, 3},{"a2", 2, 3},{"w2",1, 3},{"i2", 3, 1},{"a1", 2, 4}}
--format: {itemTag, Type, Rarity}

table.sort(invToSort, function(valueA, valueB)
	return valueA[3] > valueB[3]
end)

table.sort(invToSort, function(valueA, valueB)
	return valueA[2] < valueB[2]
end)

print(invToSort)

It just example the real code does.

Maybe…

return valueA.Rarity > valueB.Rarity and valueA.Type < valueB.Type

?

I also try to that in the first attempt but wont work

I assume you want to sort by rarity and sort everything with the same rarity by type. So you have to sort it all in one go, otherwise you overwrite the previous sorting that has been done.

Something like this will do that:

table.sort(invToSort, function(valueA, valueB)
	if valueA.Rarity ~= valueB.Rarity then
		return valueA.Rarity > valueB.Rarity
	else
		return valueA.Type < valueB.Type
	end
end)
4 Likes