How do I sort a dictionary by using dates (newest to oldest)?

Here’s an example of what my unsorted table may look like:

Levels = {
    {
        Name = "Level1", 
        CreationDate = "10:59 AM - 07/10/2022", 
        Data = 353453
    },
    {
        Name = "Test123", 
        CreationDate = "12:50 PM - 02/04/2011", 
        Data = 56756978968745658
    },
    {
        Name = "Egg Race", 
        CreationDate = "7:40 PM - 12/07/2019", 
        Data = 13544645
    },
}

I am trying to figure out a way how I can sort this table from newest to oldest via the CreationDate value in the tables.

How would I achieve this?

1 Like

If this is your data, you should save the os.time() in each object. This way it’s as simple as finding the smaller value meaning older.

2 Likes
Levels = {
    {
        Name = "Level1", 
        CreationTime = 1648951766,  -- epoch time stamp (os.time)
        Data = 353453
    },
    {
        Name = "Test123", 
        CreationDate = 164894654, 
        Data = 56756978968745658
    },
    {
        Name = "Egg Race", 
        CreationDate = 164893257, 
        Data = 13544645
    },
}

So if my data was structured like this instead, how would I go about using table.sort() for this?

I have no idea how to use table.sort(), so I am clueless on how to do this.

Tbh in this case it would probably just be fine to make your own solution by making a auxiliary table and finding and removing the smallest creating date. then placing this into the first of the aux table then set old table to aux table and clear aux table memory.

1 Like

This is how I was able to accomplish what you wanted,

Levels = {
	{
		Name = "Level1", 
		CreationDate = 1648951766,  -- epoch time stamp (os.time)
		Data = 353453
	},
	{
		Name = "Test123", 
		CreationDate = 164894654, 
		Data = 56756978968745658
	},
	{
		Name = "Egg Race", 
		CreationDate = 164893257, 
		Data = 13544645
	},
}

table.sort(Levels, function(a, b)
	return a.CreationDate < b.CreationDate
end)

for i,v in pairs(Levels) do
	print(v.Name, v.CreationDate)
end

image

Credit to the blow person: MysteriousVagabond for fixing one of my initial mistakes

2 Likes

To piggy-back off of @Inf_idel, your level tables can maintain your original structure, and the sort function can be changed to…

table.sort(Levels,function(level1,level2)
	return level1.CreationTime < level2.CreationTime
end)

…so long as the CreationTime fields are numerical.

2 Likes

Totally forgot thats how you did that, I’ll update what I had just incase its marked as the solution people aren’t confused.

2 Likes