How to sort an array which contains Dictionaries?

前端 未结 5 379
Happy的楠姐
Happy的楠姐 2020-12-30 20:05

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

相关标签:
5条回答
  • 2020-12-30 20:39

    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];
    
    0 讨论(0)
  • 2020-12-30 20:43

    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"]];
    }];
    
    0 讨论(0)
  • 2020-12-30 20:48
     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)
    
    0 讨论(0)
  • 2020-12-30 20:55

    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];
    
    0 讨论(0)
  • 2020-12-30 20:58

    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.

    0 讨论(0)
提交回复
热议问题