Hello,
The name may not describe this question perfectly, so I will explain further.
I am using the GetChildren() function to get the children of a model:
local cSets = Sets:GetChildren()
As you can see, I have each pair named “1”, “2”, etc. I want the GetChildren() function to sort the array by the names, but it instead sorts by the order that the children were added. Is there a way to make GetChildren() sort by name? If not, is there a simple way to sort an array, like a simple function I could run?
The full code snippet:
local Sets = workspace:WaitForChild("Sets")
local cSets = Sets:GetChildren()
for i,v in pairs(cSets) do
print(v.Name)
end
Output:
18:46:20.687 1 - Server - Handler:5
18:46:20.687 2 - Server - Handler:5
18:46:20.687 4 - Server - Handler:5
18:46:20.687 3 - Server - Handler:5
The only reason I didn’t do that initially was because I was hoping there would be something similar to table.sort() that I could use. That works well though, so I’ll just use it.
You can use table.sort with a custom sorting function if you prefer. It accepts that as a second argument. Here’s a quick example of how it could look:
local children = x:GetChildren() -- whatever
table.sort(children, function(child1, child2)
-- return true if `child1` should be before `child2` in the table, and let table.sort handle the actual sorting
return tonumber(child1.Name) < tonumber(child2.Name)
end)