How to sort an array which contains Dictionaries? - objective-c

I have an array which contains dictionaries in it; so how can I sort the array according to dictionary key values?

If every element in the array is a dictionary containing a certain key, you can sort the array using a sort descriptor. For instance, if every element is a dictionary containing a key called "name":
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:sortDescriptors];

The other way to achieve this would be using sortedArrayUsingComparator: method
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[obj1 valueForKey:#"value"] compare:[obj2 valueForKey:#"value"]];
}];

why don't you use a sorted dictionary where the property of sorted elements comes already with the data structure?
Please do check it out here
Hope this helps.

The above shared answer by Bavarious helped me.Just want to add one more thing.If you want to sort a mutable array use something like the below code
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
NSMutableArray *sortedArray = [[NSMutableArray sortedArrayUsingDescriptors:sortDescriptors]mutableCopy];

let arrDescriptor = NSSortDescriptor(key: "order", ascending: true)
let sortDescriptors: NSArray = [arrDescriptor]
let sortedArray = instancesubArray.sortedArray(using: sortDescriptors as [AnyObject] as [AnyObject] as! [NSSortDescriptor])
print(sortedArray)

Related

How to fetch data of NSString from array of structure hold by NSMutableArray in objective c?

I have one NSMutableArray tempArray = \[NSMutableArray array\]; which contains an array of structured objects with multiple data: brand_package_id , slide_master_id etc....
I want to sort out the tempArray according to slide_master_id's.
Please see given image and help me to sort this problem.
Try using NSSortDescriptor:
NSSortDescriptor *slideDescriptor = [[NSSortDescriptor alloc]
initWithKey:#"slide_master_id" ascending:YES];
NSArray *sortDescriptors = #[slideDescriptor];
NSArray *sortedArray = [tempArray sortedArrayUsingDescriptors:sortDescriptors];

Inserting NSDictionary into sorted NSMutableArray

I want to insert an NSDictionary object into an array and have the array sorted by objectForKey.
I managed to do this by inserting, re-sorting and reloading the array, which works fine, but I figured there would be a better method, which there is, I just don't know how to use it.
Current code:
-(NSMutableArray*)sortArray:(NSMutableArray*)theArray {
return [[theArray sortedArrayUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"n"
ascending:YES]]] mutableCopy];
}
returns the re-sorted array. Fine. Works perfectly, but... is it the most efficient?
From another question I gather that this is the method to use to find the index to insert into:
NSUInteger newIndex = [array indexOfObject:newObject
inSortedRange:(NSRange){0, [array count]}
options:NSBinarySearchingInsertionIndex
usingComparator:comparator];
[array insertObject:newObject atIndex:newIndex];
The problem is I have no idea how to use the comparator method, and if that's even possible when I want to sort by objectForKey for each index.
Can anyone exemplify the above method when the key of the object (newObject in above example) to sort by is, let's say:
[newObject objectForKey:#"sortByThis"];
Use NSSortDescriptor
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sortByThisKey" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
here is the simple example for comparator
- (NSComparisonResult)compareResulst:(CustomObject *)otherObject {
if(self.name isEqualToString:key)
{
return NSOrderedAscending;
}
else
{
return NSOrderedDescending
}
}
NSArray *sArray;
sArray = [unsArray sortedArrayUsingSelector:#selector(compareResulst:)];
this will sort the array. it will iterate through object and based on your if else it will move object up and down ...
Here's an example of sorting
//For make a we're adding 5 random integers into array inform of NSDictionary
//here, we're taking "someKey" to store the integer (converted to string object) into dictionary
NSMutableArray *array = [NSMutableArray array];
for(int i = 1; i<=5; i++) {
[array addObject:[NSDictionary dictionaryWithObject:[#(arc4random()%10) stringValue] forKey:#"someKey"]];
}
//create a sort descriptor to sort the array
//give the key in dictionary for which you want to perform sort
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"someKey" ascending:YES];
//we're doing self sort for mutable array, & that's it, you'll have a sorted array.
[array sortUsingDescriptors:#[sort]];
N.B.
1.Instead of "someKey" from above example you can set any key for which you want to perform sort.
2.There's some other methods for sorting, you can use the one base on your requirement.
3.see #[sort] in code. Its full version is, [NSArray arrayWithObject:sort];

Accessing descriptors in array of arrays

I have a mutable array containing some arrays for use in a table view controller. The arrays contain a title and some other information. I want the arrays in the master array to be sorted alphabetically in terms of the title they contain. I have assigned the titles with keys:
NSString *title = #"objectTitle";
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:_storedTitle.text, title, nil];
NSArray *newArray = #[#"Login", dict, _storedUsername.text, _storedPassword.text];
I store the newArray in my masterArray and try to sort the array thus:
//sort array alphabetically
NSSortDescriptor *titleDescriptor = [[NSSortDescriptor alloc] initWithKey:#"objectTitle" ascending:YES];
NSArray *sortDescriptors = #[titleDescriptor];
NSArray *sortedArray = [_masterArray sortedArrayUsingDescriptors:sortDescriptors];
_masterArray = sortedArray.copy;
This is not working, as i have not specified the index where the titleDescriptor is stored. How do I do this?
When accessing the title at a given index (index) in the master array is done as follows:
NSLog(#"%#", [[[_masterArray objectAtIndex:index] objectAtIndex:1] objectForKey:#"objectTitle"]);
Modified your code like this:-
NSSortDescriptor *sortedDescriptor =
[[[NSSortDescriptor alloc]
initWithKey:#"objecttitle"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)] autorelease];
NSArray * descriptors =
[NSArray arrayWithObjects:sortedDescriptor, nil];
NSArray * sortedArray =
[array sortedArrayUsingDescriptors:descriptors];
NSlog(#"%#",sortedArray);

Sort NSArray of NSDictionaries

I have a problem with sorting... I need to sort NSArray containing NSDictionaries. As an order key I have to use element from the NSDictionary.
I was reading a little about sorting NSArray but it is not clear to me.
Could you try help me?
Use an NSSortDescriptor and a keypath. Assuming the key for the dictionary is key:
NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:#"key" ascending:YES];
NSArray *sorted = [array sortedArrayUsingDescriptors:[NSArray arrayWithObject:sd]];

Objective-C NSMutableArray: Organize array of photos by date key

I have an array of dictionaries..looks like this.
(
{name = somename;
date = NSDate;
other_params = some other params;
},
...
)
How can I then sort the array items by NSDate (oldest to newest or vice versa). Do I just do a basic select-sort algorithm or is there a shorter way?
You can sort the array using descriptors or using comparators, whatever you feel more comfortable with. Here is an example of using comparators:
NSArray *sortedArray = [myArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
return [[obj1 date] compare:[obj2 date]];
}];
Here's the sort descriptors option:
// Adjust the 'ascending' option to invert the sort order.
NSSortDescriptor *dateSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"date" ascending:YES];
// The sort descriptors have to go into an array.
NSArray *sortDescriptors = [NSArray arrayWithObject:dateSortDescriptor];
NSArray *sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
You can also sort in place if you're using an NSMutableArray and don't need to keep its original order.