Find smallest Value in Table

Ok so say you have a table like this

local TableOfTeams = {
Blue Team = 1,
Red Team = 3,
Green Team = 2,
Yellow Team = 1
}

How would I get the team with the lowest value? I’ve done some research and I do know about math.min, but the problem is, is that I need to get the team name too.

I basically need it to find the team with the lowest value, and then return the team name.

I’ve been struggling with this so if you help, thanks in advance

You can create an algorithm to do a linear search for the lowest value. So something like the following can be implemented

lowest_value = table[0]

for value in table do
     if value < lowest_value
          lowest_value = value
     end
end

Of course, if you have a tie, you can have a random number generator to determine which team is selected.

1 Like
local TableOfTeams = {
   ["Blue Team"] = 1,
   ["Red Team"] = 3,
   ["Green Team"] = 2,
   ["Yellow Team"] = 1
}

local smallestTeam, smallestScore

for team, score in TableOfTeams do
   if not smallestTeam or score < smallestScore then
      smallestTeam = team
      smallestScore = score
   end
end
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.