Sort Array of Dictionary of Dictionary key value

181 views Asked by At

How can i sort array using Firt_name Key.

I used this Code but its not helpful.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"user.first_name"ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];

NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];

{
                "created_at" = "";
                "updated_at" = "";
                user =             {
                    "first_name" = Gary;
                    "full_contact" = "null 5555555555";
                    "full_name" = "Gary123";
                };
     },
2

There are 2 answers

1
Narendra Pandey On

by using NSSortDescriptor you can do that.

An NSSortDescriptor object describes a basis for ordering objects by specifying the property to use to compare the objects, the method to use to compare the properties, and whether the comparison should be ascending or descending. Instances of NSSortDescriptor are immutable.

 +(NSMutableArray *)SortArray : (NSMutableArray *)arrOriginal{
        NSSortDescriptor *sortDescriptor;
        sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Firt_name" ascending:YES
            comparator:^(id obj1, id obj2) {
            return [obj1 compare:obj2 options:NSNumericSearch];
            }];
        NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
        NSArray *sortedArray;
        sortedArray = [arrOriginal
                       sortedArrayUsingDescriptors:sortDescriptors];
        [arrOriginal removeAllObjects];
        [arrOriginal addObjectsFromArray:sortedArray];
        return arrOriginal;
    }

Hope it will be helpful.

0
Ronak Chaniyara On

Can you try below lines of code and check:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"user.first_name" ascending:YES];

NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

NSArray *sortedArray=[array sortedArrayUsingDescriptors:sortDescriptors,nil]];

You can read more about NSSortDescriptor at below link:

https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/SortDescriptors/Articles/Creating.html#//apple_ref/doc/uid/20001845-BAJEAIEE