What is the best way for me to sort a dictionary by number?

Hello developers!

I am currently developing a game in which players can score other players. At the end of the round, all the scores are tallied into a variable called FinalScores. This is a dictionary, here’s an example of what it could look like at the end of a round:

-- [USERID] = SCORE
FinalScores = {
    [235326] = 134;
    [326532632] = 325;
    [32124] = 533;
    [5848423] = 1124;
}

I’ve been trying to work out a way to sort this dictionary so I can get the placings of each players, and I haven’t found a solution yet. Storing them in an array doesn’t necessarily work in this case, because 2 players may have the same score.

Does anyone have a solution for this? Thanks!

You can use the table.sort function to return a sorted table. Here is an example

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

The function is what sorts the values. In this example, it’s checking if a is greater than b

Here is the documentation

I didn’t think this worked with dictionaries?

You can use a sorting algorithm, here’s a good post about them.

But what @TheBrainy06 suggests would be way easier.

1 Like

Maybe try storing the score like this

local scores = {
{UserId, Score},
{UserId, Score}
}

How would I sort that?

Could you maybe elaborate on how I can apply that article to a dictionary?

You can use something like this

table.sort(ScoreTable,function(a,b)
   return a[2] > b[2] 
end
1 Like

Those are methods you can use to sort large amounts of data if table.sort() doesn’t work for what you need. It’s a bit more complex than just using sort though.

So basically what my example does is it checks if the 2nd key of the first table is greater than the 2nd key of the second table and will automatically sort it.

Oh that reply was directed not at you but at @ComplicatedParadigm :smiley:
I am testing your solution now actually.

1 Like