Sorting NSArray of dictionaries by value of a key in the dictionaries

IosObjective CSortingNsarrayNsdictionary

Ios Problem Overview


I have an array populated by dictionaries, and I need to sort the array alphabetically by the values of one of the keys of the dictionaries.

This is my array:

tu dictus: (
    {
    brand = Ryul;
    productTitle = Any;
    quantity = 1;
    subBrand = "Ryul INJ";
    type = Product;
},
    {
    brand = Trol;
    productTitle = Different;
    quantity = 2;
    subBrand = "";
    type = Brand;
},
    {
    brand = Dtor;
    productTitle = Any;
    quantity = 1;
    subBrand = "";
    type = Product;
},
    {
    brand = Ryul;
    productTitle = Different;
    quantity = 2;
    subBrand = "Ryul CHES";
    type = SubBrand;
},
    {
    brand = Anan;
    productTitle = Any;
    quantity = 1;
    subBrand = "";
    type = Product;
}
)

Normally for sorting an array I will use

myArray = [uniqueProdsArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

But how do sort using the brand key of the dictionary?

Ios Solutions


Solution 1 - Ios

I think this will do it:

brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];

I pulled the code from Sort Descriptor Programming Topics. Also, Key-Value Coding comes into play, in that sortedArrayUsingDescriptors: will send a valueForKey: to each element in myArray, and then use standard comparators to sort the returned values.

Solution 2 - Ios

We Got The Solution By Using The Method Follows

[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];

Where:-

jsonData - MutableArray Which holds the Parsed JSON Data.

fullname - the data we want to sort.

id - An unique data which comes with the inner dictionary.

Solution 3 - Ios

 arrSorted = [arrBrand sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
            if ([[obj1 valueForKey:@"iUserId"] integerValue] > [[obj2 valueForKey:@"iUserId"] integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            if ([[obj1 valueForKey:@"iUserId"] integerValue] < [[obj2 valueForKey:@"iUserId"] integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        }];

Solution 4 - Ios

As an addition to QED's code,

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:@[brandDescriptor]];

This clarifies the classes of the variables and optimises the array creation with fast-enumeration. Thanks

Solution 5 - Ios

In switf:

var descriptor: NSSortDescriptor = NSSortDescriptor(key: "brand", ascending: true)
var sortedResults: NSArray = results.sortedArrayUsingDescriptors([descriptor])

Solution 6 - Ios

Use following code for sort using the "brand" key from the dictionary..

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
NSArray * sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

Use following code, If you to sorting according two keys from the dictionary; Like, "brand" key and productTitle key from the dictionary:-

NSSortDescriptor * brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];
NSSortDescriptor * productTitleDescriptor = [[NSSortDescriptor alloc] initWithKey:@"productTitle" ascending:YES];
NSArray * sortDescriptors = [NSArray arrayWithObjects:brandDescriptor, productTitleDescriptor, nil];
NSArray * sortedArray = [feedData sortedArrayUsingDescriptors:sortDescriptors];
NSLog(@"sortedArray %@",sortedArray);

Solution 7 - Ios

My code was crashing when using NSSortDescriptor so ended up using a block which works great in my use case, where I am expecting the "rank" to be an NSNumber. If the object can't be converted to an integer it will not sort but it also won't cause a crash.

NSArray *sortedArray = [data sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    long data1 = [[obj1 valueForKey:@"rank"] integerValue];
    long data2 = [[obj2 valueForKey:@"rank"] integerValue];
    if (data1 > data2) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    if (data1 < data2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];

Solution 8 - Ios

Just try it out easiest way...

myArray = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray removeAllObjects];
[tempArray addObjectsFromArray: myArray];

NSString *key = @"brand";
NSSortDescriptor *brandDescriptor = [[NSSortDescriptor alloc] initWithKey:key ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:brandDescriptor,nil];
NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];
[brandDescriptor release];
[tempArray removeAllObjects];
tempArray = (NSMutableArray*)sortedArray;
[myArray removeAllObjects];
[myArray addObjectsFromArray:tempArray];

Solution 9 - Ios

you can do this .

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"d LLLL yyyy"];

NSComparator compareDates = ^(id string1, id string2)
{
    NSDate *date1 = [formatter dateFromString:string1];
    NSDate *date2 = [formatter dateFromString:string2];
    
    return [date1 compare:date2];
};
NSSortDescriptor * sortDesc1 = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO comparator:compareDates];
[array sortUsingDescriptors:[NSArray arrayWithObjects:sortDesc1, nil]];

Solution 10 - Ios

NSSortDescriptor *brandDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"Position" ascending:YES selector:@selector(localizedStandardCompare:)] autorelease];
      NSArray *sortDescriptors = [NSArray arrayWithObject:brandDescriptor];
      NSArray  *sortedArray = [arrTemp sortedArrayUsingDescriptors:sortDescriptors];
     array_PreLagData=(NSMutableArray*)sortedArray;

unsorted array
Printing description of arrTemp:
<__NSArrayM 0x10282100>(
{
    Milker2 = "11:03:17 AM";
    Position = 2;
},
{
    Milker1 = "11:03:28 AM";
    Position = 25;
},
{
    Milker3 = "11:03:18 AM";
    Position = 3;
},
{
    Milker1 = "11:03:16 AM";
    Position = 1;
    Strip = "11:32:32 AM";
},
{
    Milker1 = "11:03:21 AM";
    Position = 10;
}
)
Sorted array
<__NSArrayI 0x101363c0>(
{
    Milker1 = "11:03:16 AM";
    Position = 1;
    Strip = "11:32:32 AM";
},
{
    Milker2 = "11:03:17 AM";
    Position = 2;
},
{
    Milker3 = "11:03:18 AM";
    Position = 3;
},
{
    Milker1 = "11:03:21 AM";
    Position = 10;
},
{
    Milker1 = "11:03:28 AM";
    Position = 25;
}
)

[enter link description here][1]


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

Solution 11 - Ios

Use this for swift 4

let sortedArray = arrayTobeSort.sorted {$0["keyName"].compare($1["keyName"]) == ComparisonResult.orderedAscending}

You can also use ComparisonResult.orderedDescending to sort in descending order

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmanuelBetancurtView Question on Stackoverflow
Solution 1 - IosQEDView Answer on Stackoverflow
Solution 2 - IosPrabhu NatarajanView Answer on Stackoverflow
Solution 3 - IosHardip KalolaView Answer on Stackoverflow
Solution 4 - IosmylogonView Answer on Stackoverflow
Solution 5 - IosHDmastView Answer on Stackoverflow
Solution 6 - IosMeet DoshiView Answer on Stackoverflow
Solution 7 - IosOffensivelyBadView Answer on Stackoverflow
Solution 8 - IosIOS RocksView Answer on Stackoverflow
Solution 9 - IosAlok ChandraView Answer on Stackoverflow
Solution 10 - IosjbchitaliyaView Answer on Stackoverflow
Solution 11 - IosAvneesh AgrawalView Answer on Stackoverflow