Getting the richest player on chat command?

I need help with my script I’m trying to figure out how I’d get the richest player from leaderstats (in the server the command is run)

Example: someone says “.richest” it would say

“MarkedTerritory is the richest in the server with $100K!”

1 Like

You can find the min or max of an array in linear time.

function getPlayerWithHighestStat(stat)
	local players = game:GetService("Players"):GetPlayers()
	local richestPlayer = players[1]
	local amount = richestPlayer.leaderstats[stat].Value
	for _, player in ipairs(players) do
		if (player.leaderstats[stat].Value > amount then
			richestPlayer = player
			amount = player.leaderstats[stat].Value
		end
	end
	return richestPlayer, amount
end

local player, amount = getPlayerWithHighestStat("Money")
print(player.Name.." is the richest in the server with $"..amount.."!")
2 Likes