How to order a nested dictionary

I am aware that you can’t order a dictionary, and that I can use a proxy array to sort it instead, but I’m not sure how I’d apply this to a nested array.

regTrails = {
	BlueTrail = {
		Name = "Blue",
		img = "rbxassetid://15638213566",
		Price = 15
	},
	BricksTrail = {
		Name = "Bricks",
		img = "rbxassetid://15638213470",
		Price = 20
	},
	RainbowTrail = {
		Name = "Rainbow",
		img = "rbxassetid://15638212155",
		Price = 50
	},
	RedTrail = {
		Name = "Red",
		img = "rbxassetid://15638212083",
		Price = 15
	}
}

Here, I am attempting to sort them by Price.

You won’t be able to sort that table because you’re identifying them with a string rather than a number. For example you could replace BlueTrail, BricksTrail, RainbowTrail and RedTrail with [1],[2],[3],[4]. Another alternative would be to just remove “BlueTrail =” all together.

Heres what I wrote, hopefully this is something you could work with.

local regTrails = {
	{
		Index = "BlueTrail",
		Name = "Blue",
		img = "rbxassetid://15638213566",
		Price = 15
	},
	{
		Index = "BricksTrail",
		Name = "Bricks",
		img = "rbxassetid://15638213470",
		Price = 20
	},
	{
		Index = "RainbowTrail",
		Name = "Rainbow",
		img = "rbxassetid://15638212155",
		Price = 50
	},
	{
		Index = "RedTrail",
		Name = "Red",
		img = "rbxassetid://15638212083",
		Price = 15
	}
}

table.sort(regTrails,function(a,b)
	return a["Price"] < b["Price"]
end)

print(regTrails)
1 Like

Damn, didn’t want to have to turn them into tables but this works as intended anyway. Thanks!

1 Like

In case you want a way to convert the dictionary you have to @CrazyCorrs array automatically:

local function regDictToArr(dict)
	local t = {}
	for index, vals in pairs(dict) do
		local trail = {Index = index}
		for i, v in pairs(vals) do trail[i] = v end
		table.insert(t, trail)
	end
	return t
end

regTrails = regDictToArr(regTrails)

table.sort(regTrails, function(a, b)
	return a["Price"] < b["Price"]
end)

print(regTrails)

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