get the key of the smallest value in a table ?

General discussion about LÖVE, Lua, game development, puns, and unicorns.
PGUp
Party member
Posts: 105
Joined: Fri Apr 21, 2017 9:17 am

Re: get the key of the smallest value in a table ?

Post by PGUp »

Code: Select all

min = 99999
Key = 0
table = {53, 36, 86}

for i, v in pairs(table) do
If v < min then
min = v
key = i
end
end

min = 99999
-
grump
Party member
Posts: 947
Joined: Sat Jul 22, 2017 7:43 pm

Re: get the key of the smallest value in a table ?

Post by grump »

PGUp, your code has multiple errors that prevent it from working as is, and it doesn't work for values > 99999. Questionable style too; uses global variables, no indentation and pairs instead of ipairs to iterate over an array. The last line of code has no obvious purpose. It even redefines the global table, making important functions unavailable. Using this code would create more problems than it solves.
User avatar
ivan
Party member
Posts: 1911
Joined: Fri Mar 07, 2008 1:39 pm
Contact:

Re: get the key of the smallest value in a table ?

Post by ivan »

Nixola has a point, if you need the KEY rather than the value then note that "pairs" makes the function non-deterministic.
You should use a numeric loop or ipairs so that the function has consistent behavior and returns the same key in the event of duplicates.
Either that or you have to ensure that there are no duplicate minimal values in the table.
Depending on what you are trying to achieve, determinism may or may not be an issue.
sphyrth
Party member
Posts: 260
Joined: Mon Jul 07, 2014 11:04 am
Contact:

Re: get the key of the smallest value in a table ?

Post by sphyrth »

My dirty solution is that you get the value of the first table item.

Code: Select all

table = {763, 365, 2010, 433}
min = table[1]
Key = 1

for i=2, #table do
   if table[i] < min then
      min = table[i]
      key = i
   end
end
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot] and 228 guests