Dictionary Sorting

I’m trying to sort a dictionary but I can’t figure out how to do this, it works on a normal table but not a dictionary, I think the problem is that a dictionary has string key’s so it can’t be sorted like a normal table that has numbered keys, but I need to be able to keep the player’s userID or username with their individual number somehow.

Code:

math.randomseed(tick())
local Table1 = {
	["Complextic"] = 1;
	["Stinger"] = 20;
	["Beluga"] = 8;
	["Iogician"] = 2;
	["LimitedUHax"] = 50;
	["Flashy"] = 7;
}

local Table2 = {
	1;
	20;
	8;
	2;
	50;
	7;
}

function Sorter(a, b)
	return a > b
end

table.sort(Table2, Sorter)

for i,v in pairs(Table2) do
	print(i, v)
end
8 Likes

A dictionary has no order so cannot be sorted. You just index a dictionary.

Yea I know that but I need an alternative to that

Flip the index/value pairs so you can index the table using the number

local Table1 = {
	[1] = "Complextic",
    [20] = "Stinger",
    [8] = "Beluga",
}

These are all numerical keys, so it can be sorted
However, I’m curious about why you need the table to be sorted-
If you wish to iterate through it in order via ipairs, you won’t be successful because there are “gaps” in the table (e.g jumps from key 2 to key 7)

I just read the title lol. Can you explain what you are using this for? You may want something like a linked list.

Did not sort at all

I’m making a hockey game and I want to be able to sort player statistics but I can’t use OrderedDataStores

If you want to get a sorted array representation of the contents of a dictionary then store all of the key, value pairs in an array.

local array = {}
for key, value in pairs(dictionary) do
	array[#array+1] = {key = key, value = value}
end
table.sort(array, function(a, b)
	return a.value > b.value
end)
39 Likes

you beat me to it XD

math.randomseed(tick())
local Table1 = {
	{90, "A"};
	{2, "B"};
	{3, "C"};
	{20, "D"};
	{5, "E"}
}

function Sorter(a, b)
	return a[1] > b[1]
end

table.sort(Table1, Sorter)

for i,v in pairs(Table1) do
	print(v[1], v[2])
end

Got it working thanks man!

3 Likes