Dilip Manek
Dilip Manek

Reputation: 9143

How to sort array using 2 key

I have array that have dictionaries, for exp..

[
  {
    name : dilip
  },
  {
    address : ahmedabad
  },
  {
    name : ajay
  },
  {
    address : baroda
  },
  {
    name : ram
  },
  {
    address : dwarka
  },
  .
  .
  .
]

Now i want to sort this array alphanumerically,Like this..

(
    {
        address = ahmedabad;
    },
        {
        name = ajay;
    },
        {
        address = baroda;
    },
        {
        name = dilip;
    },
        {
        address = dwarka;
    },
        {
        name = ram;
    }
)

But if any Dictionary does not have name than it will be sorted using address,
Any suggestion that how can we do it?

I have tried following code, but not getting proper result,

 NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
 NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"address" ascending:YES];
 NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
 NSArray * sortedArray = [ary sortedArrayUsingDescriptors:sortDescriptors];

I have 1 idea, that add address string in name and than sort array and once array sorted than will change it back to address,
But want to know is there any other option or not.

Upvotes: 0

Views: 60

Answers (1)

Fonix
Fonix

Reputation: 11597

Think this might do the trick

NSArray * sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary * _Nonnull obj1, NSDictionary *  _Nonnull obj2) {

    NSString * s1 = [obj1 objectForKey:@"name"];
    if(s1 == nil){
        s1 = [obj1 objectForKey:@"address"];
    }

    NSString * s2 = [obj2 objectForKey:@"name"];
    if(s2 == nil){
        s2 = [obj2 objectForKey:@"address"];
    }

    return [s1 compare:s2];
}];

havnt tested the code so may need some tweaking

Upvotes: 1

Related Questions