Reputation: 1974
I'm attempting to write a sort function to use with Array.sort(). I'm a bit stuck on how I can write exactly what I need though.
In my app items are added to this array at different times throughout execution, and each time an item is added, the array is sorted. The items in the Array are all objects and all have a property "weight". If a weight is greater, the item should go first, if it's less the item should go after. That is easy and I have a function that looks like this:
return a.weight - b.weight;
The problem is I have an added requirement that if an item is added later and it has the same weight as another item it MUST be put after that item in the array. It MUST go behind every item in the array that has already been added which has the same weight.
I'm having trouble coming up with a function to make sure that requirement is met every time.
Thanks for the help!
Upvotes: 3
Views: 1999
Reputation: 4583
No need for writing a custom sort, the Array's sortOn
can handle this case.
You will however need to add a new member to your items, I'll call it 'timestamp'.
arr.sortOn( [ 'weight', 'timestamp' ], [ Array.NUMERIC | Array.DESCENDING, Array.NUMERIC ] );
The first parameter defines which properties will be used for sorting, the second defines the options for each field. See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#sortOn() for more info. The |-operator (bitwise OR-operator) is used to pass multiple options for one field. So, in this case, the first field ('weight') gets sorted numerically and descending.
--EDIT:
For Vectors you need to use a comparison function:
var sortFunc : Function = function (x: <T>, y : <T>):Number{
var dw:Number = y.weight - x.weight
if( dw ==0 ){
//returns negative if y was added later
return x.timestamp - y.timestamp;
}else{
//returns negative if x has a higher weight
return dw;
}
}
vec.sort( sortFunc );
Upvotes: 6
Reputation: 13151
I would suggest to add another property to the object. Something like :
a.index = i; // where, i is the index before sorting
This will allow you to keep track of the order it entered the list before sorting.
Besides this you may also consider keeping another copy of the array itself (with index intact).
Upvotes: 1