How to sort an array which contains Dictionaries?
Asked Answered
F

5

34

I have an array which contains dictionaries in it; so how can I sort the array according to dictionary key values?

Fold answered 28/1, 2011 at 3:28 Comment(1)
this question is present in Stackoverflow #4767719Foilsman
W
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];
Wirehaired answered 28/1, 2011 at 3:47 Comment(1)
how to sort int value?Carliecarlile
A
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"]];
}];
Alius answered 6/3, 2014 at 19:3 Comment(0)
S
1

why don't you use a sorted dictionary where the property of sorted elements comes already with the data structure?

Please do check it out here

Hope this helps.

Sacking answered 28/1, 2011 at 3:32 Comment(0)
B
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];
Berger answered 18/11, 2013 at 11:38 Comment(0)
L
-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)
Lexicographer answered 23/5, 2017 at 11:43 Comment(1)
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 How to Answer.Monoatomic

© 2022 - 2024 — McMap. All rights reserved.