Sort table by contained value

Asked

Viewed 206 times

6

I want to sort such a table by a value contained in it. Ex:

tabela = {
{pessoa="Joao", idade=20},
{pessoa="Pedro", idade=22},
{pessoa="Lucas", idade=19},
{pessoa="Derp", idade=25}
}

I want to sort the table by age. Something like:

table.sort(tabela, function(table, value1, value2) return table.value1 < table.value2 end)
for x=1, table.maxn(tabela) do
print(tabela[x].idade)
end

Would return:

25
22
20
19

1 answer

8


You came close. But there are three mistakes.

  • You are receiving the parameters improperly. This lambda that the table.sort wait receives only two parameters representing the two items to be compared. These items are independent values, you do not need or can receive the table. The way you did you’re getting the table and picking up the items from it. So, in theory, you wouldn’t even need the subsequent parameters. But it’s just the opposite of what you need. This lambda cannot have the signature you want because it will be called by table.sort. It needs to conform to the established specification.

  • You are taking the whole item to compare instead of the specific item, that is, you need to get the table age and not the table the function receives. I don’t know if you noticed you have a nested table. So your anonymous function passed to the table.sort is receiving a table with the items pessoa and idade. So far so good. But you’re trying to compare the table and do not give (do not confuse with the main table, is the interior table, ex.: {pessoa="Joao", idade=20}). You need to compare a table item. This item is the idade.

  • And you showed that you want the ordination decreasing which would require the comparison to be a sign of "greater than". You would probably realize this when you solved the previous problem.

Then it would look something like this:

tabela = {
    {pessoa = "Joao", idade = 20},
    {pessoa = "Pedro", idade = 22},
    {pessoa = "Lucas", idade = 19},
    {pessoa = "Derp", idade = 25}
}
table.sort(tabela, function(value1, value2) return value1.idade > value2.idade end)
for x = 1, table.maxn(tabela) do
    print(tabela[x].idade)
end

Behold working in the ideone. And in the Coding Ground. Also put on the Github for future reference.

  • 2

    Perfect, best explanation, impossible. It worked here.

  • 1

    +1 This is a Bible for those who are learning

Browser other questions tagged

You are not signed in. Login or sign up in order to post.