I have an array which contains dictionaries in it; so how can I sort the array according to dictionary key values?
Asked
Active
Viewed 1.9k times
34
-
1this question is present in Stackoverflow http://stackoverflow.com/questions/4767219/how-to-sort-a-nsarray-which-contains-nsdictionary/4767282#4767282 – Girish Kolari Jan 28 '11 at 04:01
5 Answers
90
If every element in the array is a dictionary containing a certain key, you can sort the array using a sort descriptor. For instance, if every element is a dictionary containing a key called "name":
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];
13
The other way to achieve this would be using sortedArrayUsingComparator:
method
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 valueForKey:@"value"] compare:[obj2 valueForKey:@"value"]];
}];

dariaa
- 6,285
- 4
- 42
- 58
0
The above shared answer by Bavarious helped me.Just want to add one more thing.If you want to sort a mutable array use something like the below code
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSMutableArray *sortedArray = [[NSMutableArray sortedArrayUsingDescriptors:sortDescriptors]mutableCopy];

Baby Groot
- 4,637
- 39
- 52
- 71

Jerin
- 1
-3
let arrDescriptor = NSSortDescriptor(key: "order", ascending: true)
let sortDescriptors: NSArray = [arrDescriptor]
let sortedArray = instancesubArray.sortedArray(using: sortDescriptors as [AnyObject] as [AnyObject] as! [NSSortDescriptor])
print(sortedArray)

NeverHopeless
- 11,077
- 4
- 35
- 56

saurabh rathod
- 1,090
- 7
- 7
-
Please use the [edit] link to explain how this code works and don't just give the code, as an explanation is more likely to help future readers. See also [answer]. – Jed Fox Jun 28 '17 at 18:56