Sorting by Functions in ActionScript

Our example demonstrates how to perform custom sorting in ActionScript. We’ll sort strings by their length and custom objects by a specific property.

package {
    import flash.display.Sprite;
    import flash.utils.describeType;

    public class SortingByFunctions extends Sprite {
        public function SortingByFunctions() {
            var fruits:Array = ["peach", "banana", "kiwi"];

            // We implement a comparison function for string lengths.
            function lenCmp(a:String, b:String):int {
                return a.length - b.length;
            }

            // Now we can call Array.sort with this custom comparison function
            // to sort 'fruits' by name length.
            fruits.sort(lenCmp);
            trace(fruits);

            // We can use the same technique to sort an array of
            // custom objects.
            var people:Array = [
                {name: "Jax", age: 37},
                {name: "TJ", age: 25},
                {name: "Alex", age: 72}
            ];

            // Sort 'people' by age using Array.sort.
            people.sort(function(a:Object, b:Object):int {
                return a.age - b.age;
            });

            trace(people);
        }
    }
}

To run this ActionScript code, you would typically compile it into a SWF file and then run it in a Flash Player or AIR runtime environment. The output would be similar to:

[kiwi, peach, banana]
[{name:TJ, age:25}, {name:Jax, age:37}, {name:Alex, age:72}]

In this ActionScript version:

  1. We use ActionScript’s built-in Array.sort() method, which accepts a comparison function.

  2. The comparison function for string lengths (lenCmp) is implemented as a local function within the constructor.

  3. For sorting custom objects, we use an anonymous function directly in the sort() call.

  4. ActionScript doesn’t have a built-in cmp.Compare function, so we simply subtract the values to achieve the same effect.

  5. Instead of a Person struct, we use anonymous objects with name and age properties, which is more common in ActionScript.

  6. We use trace() for output instead of fmt.Println().

Note that ActionScript uses a different paradigm for program structure. Instead of a standalone main() function, we have a class that extends Sprite, which is a common base class for visual objects in ActionScript. The constructor of this class serves as the entry point for our code.

This example demonstrates how to perform custom sorting in ActionScript, which can be useful when you need to order data based on specific criteria in your Flash or AIR applications.