views:

227

answers:

2

How would one sort an indexed array and maintain the index association in Actionscript 3.0. The Array.sort(); method seems to reindex the array no matter what. Basically I need to recreate the arsort php function in Actionscript. Possible?

+3  A: 

To do so you would need an associative array (i.e. an Object) because when the indexes are integers flash would automatically reorder them from 0 to n as you may have noticed (This can be quite annoying in your case, but has its reasons).

If you want to keep track of the key values, a hack is to store the indexes in the value for each item in the array :

var array:Object = new Array();

array.push({index:0,name:"Tom"});
array.push({index:1,name:"Andrew"});
array.push({index:2,name:"Mark"});

array.sortOn("name");

for each(var item:Object in array)
    trace(item.index, item.name);

This will trace :

1 Andrew 
2 Mark 
0 Tom

n.b. This can be improved if your values are strong typed in a Vector instead of an Array.

Theo.T
Perfect. Thanks!
Typeoneerror
A: 

I think you may be looking for http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/Array.html#sortOn()

Ronn