How can I sort my table (parts)

  1. What do you want to achieve?
    I need a way to sort my tables (that are parts)

  2. What is the issue? Include screenshots / videos if possible!
    Table that I get in output:

                    [1] = Node18,
                    [2] = Node21,
                    [3] = Node20,
                    [4] = Node19,
                    [5] = Node1,
                    [6] = Node2,
                    [7] = Node3,
                    [8] = Node4,
                    [9] = Node5,
                    [10] = Node6,
                    [11] = Node7,
                    [12] = Node8,
                    [13] = Node9,
                    [14] = Node10,
                    [15] = Node11,
                    [16] = Node12,
                    [17] = Node13,
                    [18] = Node14,
                    [19] = Node15,
                    [20] = Node16,
                    [21] = Node17,
                    [22] = Node22,
                    [23] = Node23,
                    [24] = Node24,
                    [25] = Node25
                 }  -  Server - MoveNpcBetweenNodes:26
  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I’ve tried this:
	
table.sort(SortedTable,
	function(Value1, Value2)
		return Value1[2] > Value2[2]
	end
)

but it gave me:
14:34:23.341 2 is not a valid member of Part "Workspace.TownNpc1Nodes.WalkToPackage.WalkTo.Node25"

Please help me

Use this sort function:

table.sort(MyTable, function(Value1:Instance, Value2:Instance)
	local Name1 = Value1.Name:split("e")[2]
	local Name2 = Value2.Name:split("e")[2]
	
	return tonumber(Name1) < tonumber(Name2)
end)
1 Like

If you want this to work properly, you may want to slightly modify your code to be something like the following:

table.sort(SortedTable,
    function(Value1,Value2)
        return tonumber(string.split(Value1.Name, "Node")[2]) > tonumber(string.split(Value2.Name, "Node")[2])
    end

It’s a bit of a hacky workaround, but what this does is get the number corresponding to the name of the part, and then turning it into a number, doing this process with the other value and then comparing them.

Note that this little workaround will only work if all of the components of your table are Instances that start with the name Node. Otherwise you may get an error, or there may be a faulty comparison.

1 Like

This will make it sort from greatest to least fyi

1 Like

Thanks, I’ve updated it so it’s accurate.

Thanks a lot @tinctoriall !

(Just so you know it was < not > , because my npc goes from Node1 - last node)

1 Like

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