Showing posts with label ascending. Show all posts
Showing posts with label ascending. Show all posts

Monday, January 23, 2017

Swift 3.0 Sorting Dictionary based on values

In my Objective C Sorting NSDictionary based on Values tutorial, I have explained Dictionary sorting based on values using Objective C. In this tutorial let's see the same functionality using Swift 3.0.

  
   let isAscending = false

   let dict = [

          "AAAA" : Int(2500),
          "BBBB" : Int(3200),
          "CCCC" : Int(2800),
          "DDDD" : Int(1200)

   ]


I have taken a Dictionary with keys as Strings and values as Ints. I have also taken a flag(isAscending) to configure the order.

  
    let sortedDict = dict.sorted {(_ obj1: (key1: String, value1: Int), 
                                              _ obj2: (key2: String, value2: Int)) -> Bool in
    
         let val1 = (obj1.value1)
         let val2 = (obj2.value2)
    
         if (isAscending) {

             if((val1 < val2)) {
                return true
              }

         }

         else {

             if((val1 > val2)) {
                return true
            }

         }
    
      return false
    
  }


  print (sortedDict)

  isAscending = false  :- [("BBBB", 3200), ("CCCC", 2800), ("AAAA", 2500), ("DDDD", 1200)]
  isAscending = true   :- [("DDDD", 1200), ("AAAA", 2500), ("CCCC", 2800), ("BBBB", 3200)]
       




Hope this post is useful. Feel free to comment incase of any queries.



Friday, December 30, 2016

Objective C Sorting NSDictionary based on Values

We often need to sort the key value pairs based on the value and have the keys to run the show. In this post let’s discuss Dictionary sorting based on values.

  
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:2500], @"AAAA",
                                              [NSNumber numberWithInt:3200], @"BBBB",
                                              [NSNumber numberWithInt:2800], @"CCCC",
                                              [NSNumber numberWithInt:1200], @"DDDD",                                                                                                        nil];


I have taken a dictionary which is having key value pairs. The values are numbers. I need to sort(Ascending / Descending) those values and have the sorted keys ready.

The sorting could be Ascending or Descending. So let me take a function and pass my sorting type as shown below.

  
  - (void)sortDict:(BOOL)isAscending {
    
      NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                              [NSNumber numberWithInt:2500], @"AAAA",
                                              [NSNumber numberWithInt:3200], @"BBBB",
                                              [NSNumber numberWithInt:2800], @"CCCC",
                                              [NSNumber numberWithInt:1200], @"DDDD",
                                                                                                        nil];
    
      NSArray *sortedKeys = [dict keysSortedByValueUsingComparator: 
                                                                             ^(id obj1, id obj2) {
            if(isAscending){
               return [obj1 compare:obj2];
            }
            else {
                return [obj2 compare:obj1];
            }

       }];
    
      NSLog(@"Sorted Keys: %@",sortedKeys.description);    

  }


Technically we can use keysSortedByValueUsingComparator method of NSDictionary to do this and based on the sorting type passed we need to change the comparison in the block.

  
       if (isAscending) {
           return [obj1 compare:obj2];
       }

       else {
           return [obj2 compare:obj1];
       }



  
 Ascending :

     Sorted Keys: (
     BBBB,
     CCCC,
     AAAA,
     DDDD
     )

 Descending :

     Sorted Keys: (
     DDDD,
     AAAA,
     CCCC,
     BBBB

     )


As simple as that. Now you have your Dictionary keys in your sorted order.


Hope this post is useful. Feel free to comment in case of any queries.


Friday, September 18, 2015

Objective C NSSortDescriptor

Objective C sort descriptors are very useful for sort options on a list in our applications. 

For example, we got a list of employees from server and we need to display it in a list including sort options like name, salary, experience of the employees.

For that, I am creating employee class for employee information as below.


@interface employee : NSObject

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *employeeID;
@property (nonatomic, assign) int salary;
@property (nonatomic, assign) int totalExperience;
@property (nonatomic, assign) int yearOfJoining;
@end 

As we need to display all the employees in a table view, I am taking an array and adding all the employee objects to it as shown below.


NSMutableArray *employees = [[NSMutableArray alloc] init];
    
    employee *emp1 = [[employee alloc] init];
    [emp1 setName:@"john"];
    [emp1 setEmployeeID:@"101"];
    [emp1 setSalary:12000];
    [emp1 setTotalExperience:5];
    [emp1 setYearOfJoining:2000];
    
    employee *emp2 = [[employee alloc] init];
    [emp2 setName:@"smith"];
    [emp2 setEmployeeID:@"102"];
    [emp2 setSalary:18000];
    [emp2 setTotalExperience:8];
    [emp2 setYearOfJoining:2003];
    
    employee *emp3 = [[employee alloc] init];
    [emp3 setName:@"paul"];
    [emp3 setEmployeeID:@"103"];
    [emp3 setSalary:8000];
    [emp3 setTotalExperience:2];
    [emp3 setYearOfJoining:2001];
    
[employees addObject:emp1];[employees addObject:emp2];[employees addObject:emp3];

I will use this employees array for displaying employees in a table view. 

What If I want to sort employees by name? As per the addition of employee objects, the order of employees display will be as shown below. 

NSLog(@"Before : %@",[employees valueForKeyPath:@"name"]);

Before : (
    john,
    smith,
    paul
)

Obviously, this is not in alphabetical order. Let's see how we can sort the names using NSSortDescriptor.

NSSortDescriptor *sortDescriptor = [NSSortDescriptor
                                                           sortDescriptorWithKey:@"name"
                                                           ascending:YES];

NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
employees = [[employees sortedArrayUsingDescriptors:sortDescriptors] mutableCopy];

NSLog(@"After : %@",[employees valueForKeyPath:@"name"]);

After : (
    john,
    paul,
    smith
)

Looks so simple right? Simple but powerful class for all the sort options. If you observe, I have given the key as name which is the property of employees class and applied that sort descriptor on the employees array. We can choose sort order also by playing with the ascending property.

Similarly we can apply sort on salary and experience of the employees also.

NSSortDescriptor *sortDescriptor = [NSSortDescriptor
                                                           sortDescriptorWithKey:@"salary"
                                                           ascending:YES];

NSSortDescriptor *sortDescriptor = [NSSortDescriptor
                                                           sortDescriptorWithKey:@"totalExperience"
                                                           ascending:YES];



Thanks for reading this article. Hope you found it useful :)