Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

how do I find the closest value in a dictionary?

how would I find the value in a dictionary that's closest to the money that player has? for example,if a player has 25 money I want them to be ranked as "Experienced" but when they have 51 money I want them to be ranked as "Advanced".

local ranking = {
	["Rook"] = 0,
	["Experienced"] = 20,
	["Advanced"] = 50,
	["Multimillionaire"] = 100,
	["Roblox"] = 200
}

game.Players.PlayerAdded:Connect(function(plr)
	local PlayerRank = plr.StatFolder.Money
	for i,v in next, ranking do
		if PlayerRank.Value >= v then
			plr.leaderstats.Rank.Value = i
		end
	end
end)

1 answer

You probably want to use a sorted array instead of a dictionary. This makes our job easier:

local ranking = {
    {rank = 0, name = "Rook"},
    {rank = 20, name = "Experienced"},
    {rank = 50, name = "Advanced"},
    {rank = 100, name = "Multimillionaire"},
    {rank = 200, name = "Roblox"},
}

game.Players.PlayerAdded:Connect(function(plr)
    local PlayerRank = plr.StatFolder.Money
    for i, v in ipairs(ranking) do -- Iterate over the table in order
        if v.rank >= PlayerRank then
            -- We've found the smallest rank that is above the player's rank
            if i == 1 then
                -- The smallest rank above the player's rank is the first rank.
                -- Thus the first rank is closest to the player's rank.
                plr.leaderstats.Rank.Value = v.name
                break
            end
            local distance_to_this = math.abs(v.rank - PlayerRank)
            local prev = ranking[i - 1]
            local distance_to_prev = math.abs(prev.rank - PlayerRank)
            -- If distance to v is smaller than distance to previous rank, pick v. Otherwise pick previous rank.
            local closest_rank = distance_to_this < distance_to_prev and v or prev
            plr.leaderstats.Rank.Value = closest_rank.name
        end
    end
end)

This discussion is preserved as it was. New answers, comments, and votes are closed.