I have array of dictionaries that have NSNumber for key @"id". I want to sort this array based on @"id" value. How can I do it?
Asked
Active
Viewed 490 times
3 Answers
1
You can do this easily with -[NSArray sortedArrayUsingComparator:]
and a comparison block.
The comparison block needs to return NSComparisonResult
. Fortunately, your values associated with key "id" are NSNumber
s, so simply return the result of -[NSNumber compare:]
.
// Example array containing three dictionaries with "id" keys
NSArray *unsortedArray = @[@{ @"id": @3 }, @{ @"id": @1 }, @{ @"id": @2 }];
NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1[@"id"] compare:obj2[@"id"]];
}];

Rob Bajorek
- 6,382
- 7
- 44
- 51
1
You can sorting dictionary using NSSortDescriptor. Please try this :
// Example array containing three dictionaries with "id" and "name" keys
NSArray *unsortedArray = @[@{ @"id":@3, @"name":@"abc"}, @{ @"id":@1, @"name":@"123" }, @{ @"id": @2, @"name":@"xyz" }];
NSLog(@"Unsorted Array === %@", unsortedArray);
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
initWithKey: @"id" ascending: YES];
NSArray *sortedArray = [unsortedArray sortedArrayUsingDescriptors: [NSArray arrayWithObject:sortDescriptor]];
NSLog(@"Sorted Array ==== %@", sortedArray);

Nikunj Agola
- 484
- 3
- 6
0
NSArray is immutable so to sort your array you can replace it with a sorted version like this:
NSArray * myArray = SortArray(myArray);
// SortArray works like this.
// Helper function.
NSInteger MyComparisonFunction(id a, id b, void* context) {
NSNumber *aNum = (NSNumber*)a[@"id"];
NSNumber *bNum = (NSNumber*)b[@"id"];
return [aNum compare:bNum];
}
NSArray* SortArray (NSArray* unsorted) {
return [unsorted sortedArrayUsingFunction:MyComparisonFunction context:nil];
}
Another method would be to instead use an NSMutableArray and then sort that in a similar way.

w0mbat
- 2,430
- 1
- 15
- 16