How to get the maximum value in the table

Suppose I have a table value:

{
    wsyong11 = 100,
    erichen = 100,
    eugenekoo13 = 34,
    wsyong12 = 62,
}

how can i get the maximum value?
like:

local Table = {
    wsyong11 = 100,
    erichen = 100,
    eugenekoo13 = 34,
    wsyong12 = 62,
}

print(GetMaximumValue(Table)) --> wsyong11 100 or erichen 100

Thanks for reading this question

Use this:

table.sort(Table, function(a, b)
    return a > b
end)

Try searching up the question before you make a topic, my source: Ordering a table from largest to smallest?

3 Likes

That would not work, table.sort only works with arrays, not with dictionaries.
You should convert that dictionary into an array:

local Table = {
    {"wsyong11",100}, -- name,value
    {"eriche",100},
    {"eugenekoo13",34},
    {"wsyong12",62}
}

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

Using that function on dictionaries would do nothing:

local Table = {
	wsyong11 = 100,
	erichen = 100,
	eugenekoo13 = 34,
	wsyong12 = 62,
}

--Useless here, since it is a dictionary
table.sort(Table, function(a, b)
	return a > b
end)

for a,b in pairs(Table) do
	print(b)
end
--No order, it'd print those randomly.

@wsyong11
@domboss37

This wouldn’t even work since table.sort() is exclusive to arrays only.

local function SortDictionary(Dictionary)
	local Array = {}
	for Key, Value in pairs(Dictionary) do
		table.insert(Array, {Key, Value})
	end
	table.sort(Array, function(Left, Right) return Left[2] > Right[2] end)
	return Array
end

local Result = SortDictionary{A = math.random(), B = math.random(), C = math.random()}
for _, Value in pairs(Result) do
	print(Value[1], Value[2])
end

image

1 Like