PDA

View Full Version : Sorting Percentages

st1tch
11-28-2006, 01:18 PM
I have an array that look like the following

var a:Array = [{Letter:"A", Percentage:"1%"},{Letter:"B", Percentage:"2%"},
{Letter:"C", Percentage:"10%"},
{Letter:"D", Percentage:"11%"},
{Letter:"E", Percentage:"3%"}]

I want to sort this array on Percentage, what i get is 1%, 10%, 11%, 2%, 3%, this is due because the sort function is taking the percentage data as string. I tried to build my own custom sort function but still i cant seem to get it work, i tried to substring the % from the data and sort the rest as number but its not working

So if anyone can help me i would be more than thankful

Regards;
S.

foo2
11-28-2006, 01:31 PM
var a:Array = [{Letter:"A", Percentage:"01%"},{Letter:"B", Percentage:"02%"},
{Letter:"C", Percentage:"10%"},
{Letter:"D", Percentage:"11%"},
{Letter:"E", Percentage:"03%"}]
a.sortOn("Percentage")

Or use numbers instead of strings than you mustn’t use zero.

st1tch
11-28-2006, 01:33 PM
What if i want to leave the display as it is, 1% instead of 01% and without touching the data because this is my case :S
can i do it ?

Regards
S.

Tink
11-28-2006, 09:06 PM
you should be able to do it with a custom method used in to sort the data.
var a:Array = [{Letter:"A", Percentage:"01%"},{Letter:"B", Percentage:"02%"},
{Letter:"C", Percentage:"10%"},
{Letter:"D", Percentage:"11%"},
{Letter:"E", Percentage:"3%"}]
a.sortOn(customSort);

private function customSort( a:Object, b:Object ):Number
{
var aPercent:Number = Number( a.Percentage.substr( 1 ) );
var bPercent:Number = Number( b.Percentage.substr( 1 ) );

if( aPercent > bPercent )
{
return 1;
}
else if( aPercent < bPercent )
{
return -1;
}
else
{
return 0;
}
}