Flash sortOn coolness ...
Dr. B. | Thursday, August 10, 2006
sortOn()function within Flash's Array class.
I come from a Java background, and Java's Collections API includes very sophisticated hooks to sort objects in any number of ways. I didn't expect to find that in ActionScript. So, when I had a list of objects that I needed to sort, I was pleasantly surprised to find
sortOn(), which sorts an Array of objects.
I frequently create value objects to represent things in Flash applications. In one application, I'm placing a number of animals on the stage. The environment is kinda 3D, so animals that have a lower Y axis value are farther away in the distance, while higher Y values are closer to the viewer. The Y axis value is randomly determined, so the order is not pre-determined.
Here's a simplified version of the Animal value object with only the properties relevant to this post:
// more props
// Init stuff ...
The application reads user-defined animals from the server, and randomly places these animals on the stage. I keep all the Animal objects in an array for later use.
So, I knew that in Java I could sort these Animal objects by implementing the Comparable interface. I was pretty sure I couldn't write a Comparator in ActionScript. But, I decided to check out the Array object just in case.
Then, I found the sortOn() function. Its whole purpose is to let you sort arrays of objects. It has several flavors which you can read about at the link above, but the one relevant to this lets you pass in one or more fields (object properties), and an optional sort type parameter.
Here's an example:
var animals:Array = loadAnimals();
Since initY is a property of every object in the animals array, the
sortOn()function sorts the objects on that field. By default,
sortOn()sorts in ASCII order, which is fine for strings, but bad for numbers since 100 would be sorted before 99. So, ActionScript offers options like the Array.NUMERIC constant shown above, which tells
sortOn()to sort the properties as numbers.
So, thanks ActionScript team for putting that in there -- it was a nice surprise!
Doug Smith, Senior Developer, Barefoot