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 = {Vector3.new(25, 25, 25), Vector3.new(50, 20, 75), Vector3.new(-10, 5, -15),}

-- After sorting:
Array = {Vector3.new(-10, 5, -15), Vector3.new(25, 25, 25) Vector3.new(50, 20, 75)}

How would I do this?

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

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

3 Likes