"Equip Best" button not working!

Hello everyone!

I am making an “equip best” pet system in my simulator game. Unfortunately, it is not working!

I am looping through all of the pets the player has and putting that into a table. I then filter the first x (the number of pets a player can equip at once) terms in the table and put it into a new table. I then run the onEquip() function on each of the pets. The problem is that if a player has the same pet in their inventory and they both are the best pet in the game, either only one of them will get equipped, or none of them will get equipped!

I problem right now is that when I press the “equip best” button, it starts equipping random pets.

Function:

local function equipBest()
	local pets = {}
	local newPets = {}
	
	local maxPetsEquipped = player.Values.MaxPetsEquipped.Value
	
	for i, pet in pairs(container:GetChildren()) do
		if not pet:IsA("GuiButton") or pet.Name == "Template" then continue end
		
		local petName = pet.Name
		
		table.insert(pets, petName)
	end
	
	for i = 1, maxPetsEquipped do
		table.insert(newPets, pets[1])
		table.remove(pets, 1)
	end
	
	print(pets)
	print(newPets)
	
	for i, v in newPets do
		onEquip(v)
	end
end

Please help!
Thanks

-GreenTreeGaming