简体   繁体   中英

How to sort array which has array and dictionary with date Key

I want to sort an array. here is my Array structure.

(

  (

      //SubArray
  )

 {
  date =“2016-03-16”;
 }

)

------
------

How to sort using sort descriptor?

Is it possible ? (or)

Shall i need to change my array structure.(moving sub array to dictionary..).

Take your dictionary into an Array and do this

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"date"  ascending:YES];
yourArray=[yourArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
dictionaryArray = [yourArray copy];

Below is my Answer try this if it help, it long solution but it help me to get array which is short wise date

// my Json responce in string
    NSString *Str = @"{\"Array\":[{\"date\":\"01/15/2016\",\"Subarr\":[\"A\",\"B\"]},{\"date\":\"01/06/2016\",\"Subarr\":[\"C\",\"D\"]},{\"date\":\"16/02/2015\",\"Subarr\":[\"E\",\"F\"]},{\"date\":\"22/02/2016\",\"Subarr\":[\"G\",\"H\"]}]}";
    // convert in to nsdata
    NSData *data = [Str dataUsingEncoding:NSUTF8StringEncoding];
    // final json responce
    id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    // create a new Dictionary for shorting
    NSMutableDictionary *Dic = [[NSMutableDictionary alloc] init];
    // get all main array
    NSArray *Temp1 = [json valueForKey:@"Array"];
    for (int  i = 0; i<Temp1.count; i++) {
        id subjson = Temp1[i];
        // get date and store in key string
        NSString *Key = [subjson valueForKey:@"date"];
        // get sub array and store in array object
        NSArray *Object = [subjson valueForKey:@"Subarr"];
        // now store object with key is date
        [Dic setObject:Object forKey:Key];
    }
    // after get all key from created Dictionary
    NSArray *keys = [Dic allKeys];
    // short key date wise
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
        NSDateFormatter *format = [[NSDateFormatter alloc] init];
        [format setDateFormat:@"DD/MM/YYYY"];
        NSDate *FirstDate = [format dateFromString:a];
        NSDate *SecondDate = [format dateFromString:b];
        return [FirstDate compare:SecondDate];;
    }];
    // you can get short array by date wise
    NSLog(@"%@",sortedArray);
    // now you want array which is short wise date
    NSMutableArray *Final_shortarr = [[NSMutableArray alloc] init];
    for (int  i=0; i<sortedArray.count; i++) {
        NSString *Key = [sortedArray objectAtIndex:i];
        [Final_shortarr addObject:[Dic objectForKey:Key]];
    }
    // this array give final short datewise array
    NSLog(@"%@",Final_shortarr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM