One way, sort by the founded index of the value. If you have multiple items in the table which have the same value, this method most likely won’t work
table.sort(Table, function(a, b)
return table.find(Table,a) < table.find(Table,b)
end)
Another way, sort it’s indices & individually replace the value accordingly to the sorted table of indices
local Indices = {}
for Index, _ in pairs(Table) do
table.insert(Indices, Index)
end
table.sort(Indices, function(a,b)
return a < b
end)
for _, Index in pairs(Indices) do
local Value = Table[Index]
Table[Index] = nil
Table[Index] = Value
end
You can sort dictionaries too, just compare their indices with their ASCII values…
local Indices = {}
for Index, _ in pairs(Dictionary) do
table.insert(Indices, Index)
end
table.sort(Indices, function(a,b)
return a:lower() < b:lower()
end)
for _, Index in pairs(Indices) do
local Value = Dictionary[Index]
Dictionary[Index] = nil
Dictionary[Index] = Value
end
Okay so I have a dictionary where I want to sort it in order from smallest index to highest index, and I want to retain the values of each index. The method you first provided made the value of the index the old index and got rid of the old value. The second method you provided errored with my provided table.
So you want to get the sorted version of the table but keep the original table aswell? This will work for both arrays and dictionaries…
local function SortTable(Table)
local Indices = {}
local SortedTable = {}
for Index, _ in pairs(Table) do
table.insert(Indices, Index)
end
table.sort(Indices, function(a,b)
return (type(a)=="string"and type(b) == "string" and a:lower() < b:lower())
or a < b
end)
for _, Index in pairs(Indices) do
local Value = Table[Index]
SortedTable[Index] = Value
end
return SortedTable
end
local function SortTable(Table)
local Indices = {}
local SortedTable = {}
for Index, _ in pairs(Table) do
table.insert(Indices, Index)
end
table.sort(Indices, function(a,b)
return a < b
end)
for _, Index in pairs(Indices) do
local Value = Table[Index]
SortedTable[Index] = Value
end
return SortedTable
end
local function SortTable(Table)
local SortedTable = {}
for i, v in pairs(Table) do
table.insert(SortedTable,{i,v})
end
table.sort(SortedTable, function(a,b)
return a[1] < b[1]
end)
for index, item in pairs(SortedTable) do
if item and type(item) ~= "table" then continue end
SortedTable[item[1]] = item[2]
if index ~= item[1] then
SortedTable[index] = nil
end
end
return SortedTable
end
local function SortTable(Table)
local Indices = {}
local SortedTable = {}
for Index, _ in pairs(Table) do
table.insert(Indices, Index)
end
table.sort(Indices, function(a,b)
return a < b
end)
for _, Index in pairs(Indices) do
local Value = Table[Index]
SortedTable[Index] = Value
end
return SortedTable
end
local Table = {
[1] = "hello",
[25] = "how",
[985] = "doing",
[256] = "are",
[1789] = "?",
[127] = "you"
}
for index, value in pairs(SortTable(Table)) do
print(index,value)
end