I can't piece together how to do this.
I fetch my array from a plist, this array is full of numbers (as set in the plist). Now al I need to do is sort them so they are descending, but I can't work it out.
Array.prototype.sort() The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
JavaScript Array sort() The sort() sorts the elements of an array. The sort() overwrites the original array. The sort() sorts the elements as strings in alphabetical and ascending order.
In JavaScript arrays have a sort( ) method that sorts the array items into an alphabetical order. The sort( ) method accepts an optional argument which is a function that compares two elements of the array. If the compare function is omitted, then the sort( ) method will sort the element based on the elements values.
Here is one of many methods using comparison block. This code snippet is handy for any array with numbers that you want to sort. For Ascending order:
AscendingArray = [UnsortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
For Descending order:
DescendingArray = [UnsortArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([obj1 integerValue] > [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
if ([obj1 integerValue] < [obj2 integerValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
return (NSComparisonResult)NSOrderedSame;
}];
Try this code?
NSArray *array = /* loaded from file */;
array = [array sortedArrayUsingSelector: @selector(compare:)];
The following will sort the numbers in ascending order and then reverse the result to give the numbers in descending order:
NSArray *sorted = [[[array sortedArrayUsingSelector:@selector(compare:)] reverseObjectEnumerator] allObjects];
This previous question has some other alternatives: Sort an NSArray in Descending Order
It work for me:
NSSortDescriptor *sortIdClient =
[NSSortDescriptor sortDescriptorWithKey:@"campaignValue"
ascending:NO
comparator: ^(id obj1, id obj2){
return [obj1 compare:obj2 options:NSNumericSearch];
}];
NSArray *sortDescriptors = @[sortIdClient];
NSArray *arrTemp = [self.allCampaignsList sortedArrayUsingDescriptors:sortDescriptors];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With