Sorting Values of a Dictionary

Hello! I’m working with a team to build a round-based game. At the end of the game, I generate a players individual ranking value. This value is usually in the 100s. My next step is to generate values 1-12 (12 being max players in a game) and ranking them. Using a dictionary in which the key is the username, and value is users ranking value, how could I sort the players into a numerical table? This is the code I use to generate the URV in case it’s needed. Thanks!

for y, player in pairs(players) do
			print(players[y].Name)
			local URVs = {}
			URVs[players[y].Name] = game.Players.PlayerURV:FindFirstChild(players[y].Name).Value
			print("It is " .. URVs[players[y].Name])
			
		
		end

You can use table.sort to sort your list of players you grabbed from the Players service according to their URVs, so that players with higher values come before players with lower ones.

Also, the code you provided looks like it could use a lot of fixing. For example, it just creates a URV values table not put anywhere else… Ever… For each player. I also suggest you put the PlayerURV object in ReplicatedStorage instead of the Players service.

No guarantee it works but here’s one way to do it:

local players = game.Players:GetPlayers()

-- Get the URVs as a table where keys are player names and values are URVs.
local playerUrvList = game.Players.PlayerURV
local URVs = {}
for y, player in pairs(players) do
	print(player.Name)
	URVs[player.Name] = playerUrvList:FindFirstChild(player.Name).Value
	print("It is " .. URVs[player.Name])
end

-- Sort the players list according to their URVs.
table.sort(players, function(playerA, playerB)
	return URVs[playerA.Name] > URVs[playerB.Name]
end)

-- Do something else with the "players" list afterwards.
2 Likes

The ranking is only used temporarily to offer coins, so I have no point in a long term storage. Checking out the fix now, thanks :wink: