How to sort a dictionary with floats and integers together

How would I go about sorting a table by its value similar to this?

local newTable = {
	["key"]= 0.1,
	["key2"] = 0,
	["key3"] = 0.5,
	["key4"] = 0.25,
	["key5"] = 1,
	["key6"] = 3.7,
	["key7"] = 2
	
}
local valueTable = {}
for k, v in pairs(newTable)
  table.insert(valueTable, v)

table.sort(valuetable)

local i = 1
for k, v in pairs(newTable)
  keyTable[k] = valueTable[i]
  i += 1

Key Value pairs are not designed for sorting, they are designed for easy value retrieval. They are a hash map data structure.

If your table was instead an array, where the keys are indices. Then you can sort the table in place with a single call to table.sort() instead of all the above.

ok, suppose the table above was an array with tables inside the array

local newTable = {
	{key, 0.1},
	{key2, 0.5},
	{key3, 3},
	{key4, 2.5},

	
}

Would i have the ability to sort this?

That array of tables could be sorted with a sorter function.

table.sort(newTable, function(a: {any}, b: {any}): boolean
    return a[2] > b[2]
end

You could then retrieve the appropriate keys with a function like this:

local function getKeyFromNumber(number: number): string?
    for _, numHolder in next, newTable, nil do
        if numHolder[2] == number then
            return numHolder[1]
        end
    end

    return nil
end

Yes.

table.sort(newTable, function (x, y)
     if x[2] <= y[2] then
          return true
     else return false end
)

The function parameter should return true if the X element should come before the Y element in the sorted table.

thanks for the information on how this works guys

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.