The code below should work.
But its easy to sort on distanceThe task is more complex than that. You would need to write a vlax-curve-getDistAtPoint type function for fence selections. It is doable but not easy.
The ability to change the attribute where to insert would be awesome.Updated code: