Sorting a table by values, not index

A dictionary has no inherent order, an array does. You have to create the “sorting” functionality in your own way, and there’s not just one way to do it either. Examine your use case.

If you want to get technical, Lua’s hashing function (I believe it’s modulo based in source Lua) knows the order of the indices. But, that’s more work than anyone wants to be doing just for tables.

A possible solution, or else, use the above post

Instead, why not reverse the keys and values themselves? Because two different values can share the same key, just put them together in one array and make that the value.

-- example:
[3] = {"Cart"},
[9] = {"Crates", "Torches"}

Look at your use case and you might even be able to figure out something more efficient. Let’s compare against this method:

  • Let’s assume those numbers are costs, 3$, 9$. I want to know all items that do cost $3, now I have to go through every single table and look at the key. Instead, I can just index [3] and now I have all the items that do cost $3.
  • Well even if you don’t need that feature, it’s a bonus feature. You’ll still have to look through every value just to find what you want, unless your dictionary doesn’t have just numbers as values.

(Just to be clear, outside this use case, that post is still a good method to “sort dictionaries” entirely)

If you want to look up the cost of an item, yes, this is not the best approach. But at that point, you have your original dictionary for a reason. Why do you want it sorted?

1 Like