Highest value in table

Hi, I’ve been trying to find the highest value in a table, the problem is that the table contains strings as indexes, example:

{
    ["Hi"] = 2;
    ["Bye"] = 15;
    ["Good"] = 123;
}

I wish I could find the highest value in this table, while keeping the index as it is, like this:

The Highest Value is: [“Good”] = 123
Idk if I made it clear, let me know.
Thanks!

local function getMaxKey(t)
	local maxKey, maxValue = nil, 0
	for key, value in pairs(t) do
		if value > maxValue then
			maxValue = value
			maxKey = key
		end
	end
	return maxKey
end
3 Likes

attempt to compare number < string??

Means your dictionary contains values that are strings, even though the example provided doesn’t.

1 Like
local function getMaxKey(t)
	local maxKey, maxValue = nil, 0
	for key, value in pairs(t) do
		if value > maxValue then
			maxValue = value
			maxKey = key
		end
	end
	return maxKey
end

local t = {
	["Hi"] = 2;
	["Bye"] = 15;
	["Good"] = 123;
}

local maxKey = getMaxKey(t)
print(maxKey) --Good
1 Like

I know I’m actually dumb… Btw, it returns nil?

I was in the middle of editing the first reply so you may need to copy the code again.

Since table.sort doesn’t work with indexes, I would do it like this:

local tbl = {
    ["Hi"] = 2;
    ["Bye"] = 15;
    ["Good"] = 123;
}

local wi = {}

for i,v in pairs(tbl) do
    table.insert(wi, {i, v})
end

table.sort(wi, function(a, b)
    return a[2] > b[2]
end)

print(wi[1][1] .. "has the highest value of " .. wi[1][2])
1 Like