Order NSArray of Dictionaries - Objective c - ios

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];
}];

Related

Sort an NsmutableDictionary Alphabetically [duplicate]

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);
}

how to sort array of dictionary alphabetically in iOS 9 [duplicate]

This question already has answers here:
Sorting NSArray of dictionaries by value of a key in the dictionaries
(11 answers)
Closed 6 years ago.
I am getting array of dictionary and I want to sort that data alphabetically to show indexed tableview functionality.how can i sort array with dictionary to implement indexed tableview.to sort array here is my code:
NSArray *array1 = [NSArray arrayWithArray:resultArray];
NSSortDescriptor *sortByName = [NSSortDescriptor sortDescriptorWithKey:#"first_name" ascending:YES selector:#selector(caseSensitive)] ;
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByName];
sortedArray = [array1 sortedArrayUsingDescriptors:sortDescriptors];
I am trying with code but, when i am displaying data in tableview its getting mismatch.Please suggest me correct way. Thanks.
please use this code:
NSArray *array1 = [NSArray arrayWithArray:resultArray];
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: #"self" ascending: YES];
array1 = [array1 sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
Try this
NSArray *arr = #[#{#"first_name":#"B"},#{#"first_name":#"A"}];
NSSortDescriptor *desc = [NSSortDescriptor sortDescriptorWithKey:#"first_name" ascending:YES];
arr = [arr sortedArrayUsingDescriptors:#[desc]];
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.
Ref: how to sort array of dictionary alphabetically in iOS 9
try this
let sortedKeys = (self.dictBrands.allKeys as! [String]).sort(<)
self.arrAllBrandsTitle = NSMutableArray(array: sortedKeys)

How to Modify this NSMutableArray?

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.

Getting the dictionary with the most recent date from an array of dictionaries

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];

Sort an array based on another configuration array

I have to sort an arrray according to configuration , Suppose its has some data of student which has student name
[NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:#"abc",#"name", nil],[NSDictionary dictionaryWithObjectsAndKeys:#"efg",#"name", nil][NSDictionary dictionaryWithObjectsAndKeys:#"cde",#"name", nil], nil];
and i have another array which say how to sort this array like its say first should be efg then abc and so on.
Is it possible using nsssortdescriptor or i have to write my custom code.
I would use a block to allow you to specify your comparison logic
NSArray *sortedArray = [_helpItems sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
return [(MAHelpItem *)a order] > [(MAHelpItem *)b order];
}];
self.items = sortedArray;
Perhaps this is what you're looking for:
NSArray *students;
NSArray *sortPriorities;
NSMutableArray *sortDescriptors = #[].mutableCopy;
for (NSString *key in sortPriorities) {
[sortDescriptors addObject:[NSSortDescriptor sortDescriptorWithKey:key ascending:YES]];
}
NSArray *sortedStudents = [students sortedArrayUsingDescriptors:sortDescriptors];

Resources