luaroblox-studio

lua sort table by values


how can I easily sort this table by keys? it is necessary that it displays not a key and a value, but a sorted table

for example

local mytable = {
    ["name10"] = 6,
    ["name9"] = 10,
    ["name8"] = 8,
    ["name7"] = 4,
    ["name6"] = 1,
    ["name5"] = 7, 
    ["name4"] = 2,
    ["name3"] = 3,
    ["name2"] = 5,
    ["name1"] = 9
}

it needs to return this

local sorted_table = {
    ["name9"] = 10,
    ["name1"] = 9,
    ["name8"] = 8,
    ["name5"] = 7,
    ["name10"] = 6,
    ["name2"] = 5,
    ["name7"] = 4,
    ["name3"] = 3,
    ["name4"] = 2,
    ["name6"] = 1
}

i was looking for a solution to this problem, but everywhere it gave out exactly the key and the value separately, not the table


Solution

  • Just make list, not table as :

    local mytable = {
        {name = "name10", value = 6},
        [name = "name9", value = 10},
        [name = "name8", value = 8},
    }
    

    and then sort it as usually:

    function compareValuesBackwards(a,b)
      return a.value > b.value
    end
    table.sort(items, compareValuesBackwards)