How to sort an array which contains Dictionaries?

2019-02-05 13:47发布

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

5条回答
霸刀☆藐视天下
2楼-- · 2019-02-05 14:30

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];
查看更多
ゆ 、 Hurt°
3楼-- · 2019-02-05 14:35

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"]];
}];
查看更多
劫难
4楼-- · 2019-02-05 14:38
 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)
查看更多
爷的心禁止访问
5楼-- · 2019-02-05 14:52

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];
查看更多
干净又极端
6楼-- · 2019-02-05 14:52

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.

查看更多
登录 后发表回答