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.
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:
In this ActionScript version:
We use ActionScript’s built-in
Array.sort()
method, which accepts a comparison function.The comparison function for string lengths (
lenCmp
) is implemented as a local function within the constructor.For sorting custom objects, we use an anonymous function directly in the
sort()
call.ActionScript doesn’t have a built-in
cmp.Compare
function, so we simply subtract the values to achieve the same effect.Instead of a
Person
struct, we use anonymous objects withname
andage
properties, which is more common in ActionScript.We use
trace()
for output instead offmt.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.