Sorting tables help

How would I sort this from test1 being first and test6 being last

couldn’t figure it out using table.sort()

any help would be great thanks! :slight_smile:

TestTable

you could do this

table.sort(YourTable, function(a, b)
	return tonumber(a.Name) < tonumber(b.Name)
end)
local basket = {
	fruit4 = {},
	fruit2 = {"apple"},
	fruit3 = {},
	fruit1 = {}
}

table.sort(basket, function(a, b)
	return tonumber(a.Name) < tonumber(b.Name)
end)

print(basket)

-- expected output
{
  ["fruit1"] = {},
  ["fruit2"] = {"apple"},
  ["fruit3"] = {},
  ["fruit4"] = {}
}

oh wait i just noticed you have 10s and it’ll go in order

You wouldn’t be able to use table.sort() in the case you hoped to because Test12 would return greater than Test6. Here’s an alternative method for storing the test values. You wouldn’t be able to have any test be greater than 6 if you wanted Test6 to be at the end, so you’d have to resort to decimals. Also, dictionaries have no order so you’d have to put the key and values in an array like this.

local tests = {
	{1, {}},
	{1.2, {}},
	{2, {}}
}

table.sort(tests, function(a, b)
	return a[1] <= b[1]
end)

print(tests)

Shoot i didnt want 6 to be last i meant for it to be test1 being first and test 12 being last (smallest to biggest)

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