Sorting pets strategy

Sorting pets based on equipped and increments

I wanted to sort a table of pets that have isEquipped bool and increments number in it for pets inventory.

Goals

  • Pet with isEquipped set to true always come up first.
  • Pet with higher increments always come up first.
  • Pet with isEquipped set to false always behind the pet with isEquipped set to true even if the increments is higher.

Pet object

{
  isEquipped = boolean,
  Increment = number
}

I already have this code working but im not sure if it effective (?)

function SortPets(pets)
  -- sort to the highest increment (2)
  table.sort(pets, function(a, b) 
    return a.increment > b.increment
  end)
  -- sort to equipped pets first (1)
  table.sort(pets, function(a, b) 
    return a.isEquipped and not b.isEquipped
  end)
  return pets
end

Expected output

equipped: true, increments: 4
equipped: true, increments: 3
equipped: false, increments: 4
equipped: false, increments: 1

Please reply if you have better method on sorting pets :slight_smile:

2 Likes

It’s pretty clean and efficient, nothing I would change.

UPDATE: now im able to make it simpler for sorting pets, here is the script

table.sort(petsTable, function(a, b)
	if a.isEquipped == b.isEquipped then
		 -- if both are equipped/not equipped, compare the increment
		return a.increment > b.increment
	end
	-- sort equipped pets first
	return a.isEquipped and not b.isEquipped
end)
2 Likes