The create planets method will create an return just an array of planets, each planet will just have a x and y value, as well as a radius. For now I also put in a minerals value also, but as of this writing I am not sure that I am going to go much beyond that when it comes to turning this into some kind of actual game. So then the create planets method is just a way to create a simple array of objects that contains properties that I can use to get a distance value by making use of a simple distance formula.
So the get targets method of this module is the main method of interest here with respect to the array sort method. I am looping over all the planets in the passed planets collection, and creating a target object for each planet. This target object contains things like a reference to the planet object, but also a distance value from the planet to the given point when the method is called. This distance value is then used as a way to sort the array of targets with the array sort method, and the list of targets are returned by the method.
Here I have a draw module that has a few methods to help with drawing the state of an array of targets to a canvas element. For this example I just want a draw background method, and of course a method to draw the current status with the targets list.
Some html that will pull this all together.
When this canvas example is up and running I get all the targets draw to the canvas and there is an index number for each planet drawn on each of them. At first each index number reflects the distance from the center of the canvas because of the first update call. However when I click on the canvas the index numbers change to reflect the closest and farthest planets from that given point. So simply put things seem to work as expected thus far.
So I was able to quickly throw together a little example of array.sort that might prove to be a little fun and interesting. In this example I worked out something where a list of target planets is based on distance to a given position, however this is something that can be expansed on of course. Say each planet has various levels of resources I might want a list then that is based on distance and value in terms of resources. There are many other ideas that come to might such as filtering out planets that are under control by the player, rather than neutral or enemy planets.