Search code examples
swiftnsarray

Sort a dictionary array when the key is given as the parameter


I'm working in a project in swift3 and I have an NSArray named "details" that contains NSDictionary Objects. My requirement is to sort this NSArray If a "key" is passed as the parameter (eg:- name, lastName, age). My NSArray looks like bellow.

(
 {name:"John";
  lastName :"bow";
  age: "26"; 
 },
 {
  name:"paul";
  lastName :"law";
  age: "19";
  }

)

how can I achieve this ??


Solution

  • Try this :

    NSSortDescriptor * sortDescriptors = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; // change your key here
    NSArray * arrSortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    NSArray * sortedArray = [yourArray sortedArrayUsingDescriptors:arrSortDescriptors];
    NSLog(@"sortedArray %@",sortedArray);