Sort and remove item with same name

So I’ve been trying to sort my table and remove the table with the less amount value and the same name.
Can you help me?

local mytab = {
	{["image1"] = "rbxthumb://type=AvatarHeadShot&id=637351903&w=150&h=150",
		["name"] = "Easy1",
		["timer"] = 220,
		["userid"] = 637351903,
		["username1"] = "test"},
	{["image1"] = "rbxthumb://type=AvatarHeadShot&id=637351903&w=150&h=150",
		["name"] = "Easy2",
		["timer"] = 221,
		["userid"] = 637351903,
		["username1"] = "The_KillerHood"},
	{["image1"] = "rbxthumb://type=AvatarHeadShot&id=637351903&w=150&h=150",
		["name"] = "Easy1",
		["timer"] = 221,
		["userid"] = 637351903,
		["username1"] = "test"}
}

table.sort(mytab, function(a,b)
	if a.name == b.name then
		if a.timer > b.timer then
			--remove from table
			table.remove(mytab, table.find(mytab, b))
		end
	end
	--return --what do I return???
end)


for i,v in pairs(mytab) do
	print(i,v) -- I want it to print easy1 timer: 221, easy2 timer: 221 and remove the easy1 timer: 220
end
1 Like

You were on the right track, here is the fixed version:

local mytab = {
	{["image1"] = "rbxthumb://type=AvatarHeadShot&id=637351903&w=150&h=150",
		["name"] = "Easy1",
		["timer"] = 220,
		["userid"] = 637351903,
		["username1"] = "test"},
	{["image1"] = "rbxthumb://type=AvatarHeadShot&id=637351903&w=150&h=150",
		["name"] = "Easy2",
		["timer"] = 221,
		["userid"] = 637351903,
		["username1"] = "The_KillerHood"},
	{["image1"] = "rbxthumb://type=AvatarHeadShot&id=637351903&w=150&h=150",
		["name"] = "Easy1",
		["timer"] = 221,
		["userid"] = 637351903,
		["username1"] = "test"}
}

-- Sort the table by name and timer in ascending order
table.sort(mytab, function(a, b)
	if a.name == b.name then
		return a.timer < b.timer
	else
		return a.name < b.name
	end
end)

-- Remove entries with the same name and lower timer value
local i = 1
while i < #mytab do
	if mytab[i].name == mytab[i+1].name and mytab[i].timer < mytab[i+1].timer then
		table.remove(mytab, i+1)
	else
		i = i + 1
	end
end

-- Print the updated table
for i,v in ipairs(mytab) do
	print(i, v.name, "timer:", v.timer)
end

1 Like