Sort array of Vector3s from smallest to largest

I need a way that sorts an unorganised table of vectors from smallest to largest like so:

-- Before sorting:
Array = {, 25, 25),, 20, 75),, 5, -15),}

-- After sorting:
Array = {, 5, -15),, 25, 25), 20, 75)}

How would I do this?

1 Like
table.sort(Array, function(a, b)
    return a.Magnitude < b.Magnitude

Can you explain how this works? Like what does putting a function in the paramater do? and also using return in the sort function? I have never seen return be used like this before.

1 Like

The second parameter in table.sort calls for a Lambda expression to evaluate the sort. By default it is return a > b, but it can be changed like in the example provided by @.hellish. You can utilize this to sort tables by their values, Instance properties, etc, or sort from least to greatest rather than greatest to least.

The Magnitude property of vectors is basically just the distance from the origin and the vector, no biggie