ios - Sort a NSArray of numbers in ascending order but send zeros at the end -
i have simple nsarray
, containing nsnumber
s.
i sort array in ascending order way :
nssortdescriptor *lowesttohighest = [nssortdescriptor sortdescriptorwithkey:@"self" ascending:yes]; [_scores sortusingdescriptors:[nsarray arraywithobject:lowesttohighest]];
my problem is, i'd nsnumber
s containing 0
@ end rather @ beginning. here kind of array may have sort (containing empty nsnumber
s example):
0 25 12 0 8 0
my code of course sorts array this:
0 0 0 8 12 25
what this:
8 12 25 0 0 0
of course re-order manually removing lines 0
, adding them @ end, i'm looking cleanest solution possible.
sort array using comparator.
nsarray *sortedarray = [array sortedarrayusingcomparator: ^(id obj1, id obj2) { if ([obj1 integervalue] == 0 && [obj2 integervalue] == 0) { return (nscomparisonresult)nsorderedsame; } if ([obj1 integervalue] == 0) { return (nscomparisonresult)nsordereddescending; } if ([obj2 integervalue] == 0) { return (nscomparisonresult)nsorderedascending; } if ([obj1 integervalue] > [obj2 integervalue]) { return (nscomparisonresult)nsordereddescending; } if ([obj1 integervalue] < [obj2 integervalue]) { return (nscomparisonresult)nsorderedascending; } return (nscomparisonresult)nsorderedsame; }];
Comments
Post a Comment