I have a dictionary which contain this data:
(
contact={name="Lion",id="1",photo="simba.png",address="elm street"},
{name="Cat",id="2",photo="halleberry.png",address="attic"},
{name="Bat",id="3",photo="dracule.jpg",address="long way home baby"}
)
From that NSDictionary, i grab only the name and sorted it alphabetically. Like this:
(B={"Bat"}, C={"Cat"}, L={"Lion"})
This is the code i used:
NSMutableDictionary* sortedDict = [NSMutableDictionary dictionary];
for (NSDictionary* animal in dataDict[#"user"]){
NSString* name = animal[#"name"];
if (![name length])
continue;
NSRange range = [name rangeOfComposedCharacterSequenceAtIndex:0];
NSString* key = [[name substringWithRange:range] uppercaseString];
NSMutableArray* list = sortedDict[key];
if (!list){
list = [NSMutableArray array];
[sortedDict setObject:list forKey:key];
}
[list addObject:name];
Then, what i want to ask is. What i need to create an array of photos but sorted alphabetically based on the name. I mean something like this:
(B="dracule.jpg", C="halleberry.png"...etc)
I also heard that this will be more effective to use (B={name="Bat", photo="draggle.jpg"}) but don't know how i can make something like this and don't know how to call it separately. Please i need your help :"(
You can easily sort the array which contains dictionaries values, see below
//Get the contact array.
NSArray *contacts=[dic objectForKey:#"contact"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortedArray = [contacts sortedArrayUsingDescriptors:#[sortDescriptor]];
I hope it helps.
Related
Student *s1 = [Student new];
s1.city = #"Delhi";
Student *s2 = [Student new];
s2.city = #"Mumbai";
NSArray *arrModels = #[s1,s2];
NSArray *arrCompareModel = #[#"Mumbai",#"Delhi"];
I need to sort the arrModels based on arrCompareModel.
All solutions in web are related to ascending. But here I have a custom model.
How do I achieve it?
You need to write this for sorting descending
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"city" ascending:false];
NSArray *sortedArray = [arrModels sortedArrayUsingDescriptors:#[sortDescriptor]];
Try something like that:
NSArray *sortedArray = [arrModels sortedArrayUsingComparator:^NSComparisonResult(Student *obj1, Student *obj2) {
return [arrCompareModel indexOfObject:obj1.city] < [arrCompareModel indexOfObject:obj2.city];
}];
This question already has answers here:
sort NSDictionary values by key alphabetical order
(4 answers)
Closed 6 years ago.
I have a dictionary in which, for a single key(for example key "0") there are a key value pair data.The keys are like name, id,p_id. I want to sort the NSMutableDictionary for the values related to the Key "name". The data in the dictionary is as follows,
0 = {
id = 12;
name = "Accounts ";
"p_id" = 13222071;
};
1 = {
id = 13;
name = "consultant";
"p_id" = 15121211;
};
2 = {
id = 11;
name = "Tania";
"p_id" = 10215921;
};
}
Any help is appreciated!
Please try out the below code:
[yourMutableArray sortUsingComparator: (NSComparator)^(NSDictionary *a, NSDictionary *b) {
NSString *key1 = [a objectForKey: #"name"];
NSString *key2 = [b objectForKey: #"name"];
return [key1 compare: key2];
}];
NSLog(#"Sorted Array By name key : %#", yourMutableArray);
Hope this helps!
NSArray *sortedKeys = [dict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *d1, NSDictionary *d2) {
return [d1[#"name"] compare:d2[#"name"]];
}];
NSArray *objects = [dict objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
Dictionaries are not sorted, and doesn't resemble any order. What you should do is to getAll the keys first. Then apply a sort method on the keys, then request the objects according to the ordered keys.
E.g:
NSArray *keys = [dictionary allKeys];
NSArray *sortedKeys = <sort the keys according to your preferred method>
Now you can iterate the Dictionary from the order of the array sortedKeys.
While it has been made abundantly clear that Dictionaries can't be sorted and rightfully so, that does not mean the ends you are aiming for can't be achieved. This code will do that for you:
NSArray *arrayOfDicts = dic.allValues; //Now we got all the values. Each value itself is a dictionary so what we get here is an array of dictionaries
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES]; //Create sort descriptor for key name
NSArray *sortingDesc = [NSArray arrayWithObject:nameDescriptor];
NSArray *sortedArray = [arrayOfDicts sortedArrayUsingDescriptors:sortingDesc]; //Get sorted array based on name
NSMutableDictionary *kindaSortedDict = [[NSMutableDictionary alloc] init];
int keyForDict=0;
for(NSDictionary *valDict in sortedArray)
{
[kindaSortedDict setObject:valDict forKey:[NSString stringWithFormat:#"%i",keyForDict]]; //Set values to our new dic which will be kind of sorted as the keys will be assigned to right objects
keyForDict++;
}
//Now you can simply get sorted array of keys from kindaSortedDic and results for them will always be sorted alphabetically. Alternatively you can just skip all that bother and directly use sortedArray
I have added comments in code to help you understand that.
For accessing sorted values I'd do this:
NSArray *sortedKeys = [kindaSortedDict.allKeys sortedArrayUsingDescriptors:
#[[NSSortDescriptor sortDescriptorWithKey:#"intValue"
ascending:YES]]];
for(NSString *key in sortedKeys)
{
NSDictionary *valDict = [kindaSortedDict objectForKey: key];
NSLog(#"Dict is: %# for key: %#",valDict,key);
}
I have an array of dictionaries that looks something like this
({order:1; name:foo},{order:0; name:bar}...)
And I want to order this NSArray of dictionaries by the key "order".
I know I am going to have to loop though it and then add it to a new array but Im not quite sure how to set it up?
Thanks for the help
There are several possible ways to do this.
Here's one:
NSArray *unsortedArray = ... // your unsorted array of dictionaries
NSSortDescriptor *sortBy = [NSSortDescriptor sortDescriptorWithKey:#"order" ascending:YES];
NSArray *sorted = [unsortedArray sortedArrayUsingDescriptors:#[ sortBy ]];
Here's another:
NSArray *unsortedArray = ... // your unsorted array of dictionaries
NSArray *sorted = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dic1, NSDictionary *dic2) {
NSNumber *order1 = dic1[#"order"];
NSNumber *order2 = dic2[#"order"];
return [order1 compare:order2];
}];
I have an array of objects with date inside.
Now I need to group my objects in UITableView by this date.
For examle:
0-{10-14; Obj1};
1-{10-14; Obj2};
2-{10-15; Obj3};
3-{10-15; Obj4};
I need to view it on my UITableView like this
10-14
0-{10-14; Obj1};
1-{10-14; Obj2};
10-15
2-{10-15; Obj3};
3-{10-15; Obj4};
To resolve I've done next; I've splited my array into NSDictationary with this code:
NSMutableDictionary *preResult = [[NSMutableDictionary alloc] init];
for (ClientMessage *message in array) {
NSMutableArray *mArray = [preResult objectForKey:message.formattedDate];
if (mArray == nil) {
mArray = [[NSMutableArray alloc] init];
[preResult setObject: mArray forKey:message.formattedDate];
}
[mArray addObject:message];
}
And my Table view shows me what i want, but it shows in wrong order; (my array was sorted by date)
I know tha i can't sort NSDictationary, in that case how can i sort my values in table view? Or Is there another way to group my values without NSDictationary?
Once you've finished loading the dictionary with all the values, you'll want to sort each array within the dictionary...
for (NSString *key in [preResult allKeys])
{
NSMutableArray *mArray = [preResult objectForKey:key];
// sort array to achieve the desired result
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"formattedDate" ascending:YES];
NSArray *sortedArray = [mArray sortedArrayUsingDescriptors:#[sortDescriptor]];
// reset newly sorted array for key inside the dictionary
[preResult sortedArray forKey:key];
}
I have an array of dictionaries. These dictionaries have a format like this:
NSDictionary *oneDict = #{
#"code": #"123"
#"name": #"car"
#"date": creationDate
}
these dictionaries are stored in a NSArray.
I need to extract the dictionary with the most recent date from that array.
I can discover the most recent date by doing this:
NSArray *extractDates = [array objectForKey:#"date"];
NSArray sortedDates = [extractDates sortedArrayUsingSelector:#selector(compare:)];
NSDate *mostRecentDate = (NSDate *)[sortedDates lastObject];
Now I know, I can interact over the array and look for that date, so I can get the dictionary, but I wonder if Objective-C has some sort of mechanism that can do that directly.
Try this,
NSSortDescriptor *dateDescriptor = [NSSortDescriptor
sortDescriptorWithKey:#"date"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:dateDescriptor];
NSArray *sortedArray = [array
sortedArrayUsingDescriptors:sortDescriptors];
NSDictionary *dict = (NSDictionary *)[sortedArray lastObject];