Sorting Nsarray of Dictionaries by Value of a Key in the Dictionaries

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

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.

sort NSDictionary keys by dictionary value into an NSArray

Conceptually a NSDictionary is unsorted, as said already by C0deH4cker.

If you need an order, you can either write the keys to an array (but you might have trouble with the array retaining it after the key was removed from the dictionary, but there are tutorials how to create a un-retaining array by using the CFArray) or NSSortedSet.

Or you can subclass NSDictionary — not very trivial, as NSDictionary is a class cluster. But luckily Matt shows in his fantastic blogpost "OrderedDictionary: Subclassing a Cocoa class cluster" how to use a little trick, a covered has-a relationship.


Note, that your code

 NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) {

if ( first < second ) {
return (NSComparisonResult)NSOrderedAscending;
} else if ( first > second ) {
return (NSComparisonResult)NSOrderedDescending;
} else {
return (NSComparisonResult)NSOrderedSame;
}

}];

wont do, what you want it to do, as you are applying C-operators to objects. Now their pointers will be ordered.

it should be something like

 NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) {
return [first compare:second];
}];

or if you want to order on scalars, that are wrappers as objects (ie NSNumber)

 NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) { 
if ([first integerValue] > [second integerValue])
return (NSComparisonResult)NSOrderedDescending;

if ([first integerValue] < [second integerValue])
return (NSComparisonResult)NSOrderedAscending;
return (NSComparisonResult)NSOrderedSame;
}];

Best way to sort an NSArray of NSDictionary objects?

Use NSSortDescriptor like this..

NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"interest" ascending:YES];
stories = [stories sortedArrayUsingDescriptors:@[descriptor]];
recent = [stories copy];

stories is the array you want to sort. recent is another mutable array which has sorted dictionary values. Change the @"interest" with the key value on which you have to sort.

All the best

How do I sort a list of dictionaries by a value of the dictionary?

The sorted() function takes a key= parameter

newlist = sorted(list_to_be_sorted, key=lambda d: d['name']) 

Alternatively, you can use operator.itemgetter instead of defining the function yourself

from operator import itemgetter
newlist = sorted(list_to_be_sorted, key=itemgetter('name'))

For completeness, add reverse=True to sort in descending order

newlist = sorted(list_to_be_sorted, key=itemgetter('name'), reverse=True)

Sort NSArray of NSDictionary using value

Try this :-

NSArray *aSortedArray = [itemArray sortedArrayUsingComparator:^(NSMutableDictionary *obj1,NSMutableDictionary *obj2) {
NSString *num1 =[obj1 objectForKey:@"rowID"];
NSString *num2 =[obj2 objectForKey:@"rowID"];
return (NSComparisonResult) [num1 compare:num2 options:(NSNumericSearch)];
}];

Sorting NSArray which contain array of dictionaries - Sort as per Date key

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"M/dd/yyyy H:mm:ss a"];

NSArray *sortedByDates = [arr sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2)
{
NSDate *date1 = [dateFormatter dateFromString:obj1[@"postDate"]];
NSDate *date2 = [dateFormatter dateFromString:obj2[@"postDate"]];
return [date1 compare:date2];
}];
NSLog(@"Sorted Array : %@",sortedByDates);

Sort array of NSDictionaries by a value inside one of the keys

Use the following;

NSArray *sortedArray;
sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *first, NSDictionary *second) {
// Calculate distances for each dictionary from the device
// ...
return [firstDistance compare:secondDistance];
}];

Sorting an array of dictionaries by key value

I guess sortedArrayUsingComparator: method is what you are looking for:

NSArray *array = @[@{@"location" : @"USA"},
@{@"location" : @"UK"},
@{@"location" : @"Asia"},
@{@"location" : @"UK"},
@{@"location" : @"USA"},
@{@"location" : @"Asia"}];
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 valueForKey:@"location"] compare:[obj2 valueForKey:@"location"]];
}];

Sort Array of Dictionaries by Key Value

You can resort to NSArray's sortUsingDescriptors functionality:

let sortedArray = (itemsArray as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "itemName", ascending: true)]) as [[String:AnyObject]]

Swift > 3

let sortedArray = (itemsArray as NSArray).sortedArray(using: [NSSortDescriptor(key: "itemName", ascending: true)]) as! [[String:AnyObject]]

Not very Swift-ish, and you lose the type safety, but it does it's job.

And btw, you have a lot of forced casts in your code, which have the potential of crashing your app, you should consider switching to optional ones instead.



Related Topics



Leave a reply



Submit