Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of dates in descending order

I have a NSDictionary that parsed to an array one of the element is date, i tried using [startimeArray sortUsingSelector:@selector(compare:)]; (starttimeArray) is my date but it only arrange ascending. how can i sort in descending order. thanks

like image 930
baste Avatar asked Jan 26 '13 20:01

baste


People also ask

How do you sort an array in descending?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.

How do you sort in descending order?

The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do you sort an array in order?

We can sort arrays in ascending order using the sort() method which can be accessed from the Arrays class. The sort() method takes in the array to be sorted as a parameter. To sort an array in descending order, we used the reverseOrder() method provided by the Collections class.


2 Answers

You can use a comparator block

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
    return [d1 compare:d2];
}];

to reverse the order, just swap the dates

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
    return [d2 compare:d1];
}];

or — as compare: returns a NSComparisonResult, which is actually typedef'ed to integer see below — just multiply by -1

NSArray *sortedArray = [array sortedArrayUsingComparator: ^(NSDate *d1, NSDate *d2) {
    return -1* [d1 compare:d2];
}];

enum {
   NSOrderedAscending = -1,
   NSOrderedSame,
   NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
like image 33
vikingosegundo Avatar answered Sep 18 '22 12:09

vikingosegundo


Sort the array by puting NO is ascending parameter:

NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"self" ascending:NO];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[dateArray sortedArrayUsingDescriptors:descriptors];
like image 195
Anoop Vaidya Avatar answered Sep 19 '22 12:09

Anoop Vaidya