Sort an array based on another configuration array - ios

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

Related

Sorting an array based on a compare model iOS

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

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

Objective C custom compare: with priority

I have a NSArray of countries that I obtained using [NSLocale ISOCountryCodes]. How do I sort this NSArray such that I can put certain commonly used countries at the top of the list, while keeping the rest in its alphabetical order?
United States of America
United Kingdom
Singapore
Korea
Japan
Hong Kong
Afghanistan
Albania
Algeria
etc etc..
I am using caseInsensitiveCompare: currently to get the alphabetical order, but how can I change it such that I can specify a list to put at the top, while the rest to be kept alphabetical below.
You can delete the objects you do not want to sort,then sort the rest,then add them together.
Example Code:
NSMutableArray * allData = [[NSMutableArray alloc] initWithArray:[[NSLocale ISOCountryCodes]]];
NSArray * yourexceptArray;
[allData removeObjectsInArray:yourexceptArray];
NSMutableArray * result = [[NSMutableArray alloc] initWithArray:yourexcepArray];
sortedArray = //Sort the allData as you like,then add it to result
[result addObjectsFromArray:sortedArray]
As opposed to WenchenHuang's answer (which is valid), I think you could do it with the help of sortedArrayUsingComparator.
Inside the block just compare the strings as usually, but if the string equals to one of the codes that you want to show higher, return YES.
someArray = [someArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
if ([(NSString*)obj1 isEqualToString:#"USA"]) {
return YES;
} else if ([(NSString*)obj1 isEqualToString:#"SOME_OTHER_COUNTRY"]) {
return YES;
}
return [(NSString*)obj1 compare:(NSString*)obj2];
}];
I would do it using Sort Descriptor. I don't like manipulating array again and again. So, I find sort descriptors best in this kind of scenario. (Just personal preference)
Step 1: Create a model class with priority as a key. My model class-
#import <Foundation/Foundation.h>
#interface ISOCountry : NSObject
#property(nonatomic, strong) NSString *countryCode;
#property(nonatomic, retain) NSString *priority;
#end
Step 2: The just do this-
NSArray *ISOCountryCodes = [[NSArray alloc]initWithArray:[NSLocale ISOCountryCodes]];
NSArray *commonUsedCountries= [[NSArray alloc]initWithObjects:#"NR", #"NG", #"KW", #"ES", nil];
NSMutableArray *arrayToBeSorted = [[NSMutableArray alloc]init];
for(NSString *countryCode in ISOCountryCodes){
ISOCountry *isoCountry = [[ISOCountry alloc] init];
[isoCountry setValue:countryCode forKey:#"countryCode"];
if(![commonUsedCountries containsObject:countryCode]){
[isoCountry setValue:[NSString stringWithFormat:#"%d", 2] forKey:#"priority"];
}
else{
[isoCountry setValue:[NSString stringWithFormat:#"%d", 1] forKey:#"priority"];
}
[arrayToBeSorted addObject:isoCountry];
}
NSSortDescriptor *prioritySort = [[NSSortDescriptor alloc] initWithKey:#"priority" ascending:YES];
NSSortDescriptor *countryCodeSort = [[NSSortDescriptor alloc] initWithKey:#"countryCode" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:prioritySort, countryCodeSort, nil];
NSArray *sortedArray = [arrayToBeSorted sortedArrayUsingDescriptors:sortDescriptors];

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.

Sort an NSArray by another nsarray with ids

i have 2 nsarrays
1 with nsdictionary's another with nsnumbers
NSArray *arr1 = #[#{#"id":#1},#{#"id":#2},#{#"id":#3},#{#"id":#4}];
NSArray *arr2 = #[#3,#1,#4,#2];
and i want to sort my arr1 through their id following the order of arr2
is this possible?
The problem with using sortedArrayUsingComparator: is you start dealing with O(n^2) lookup times. For each sort comparison in the first array, you have to do a lookup in the second array.
Your best bet is to take advantage of a hash table to reduce that to O(n) average complexity.
Your first step is to create a dictionary using id as a key. The result would look something like #{#1: #{#"id":#"1"}, ...}. Then you just have to construct an array by looping through arr3 and grabbing the values.
NSArray *arr1 = #[#{#"id":#1},#{#"id":#2},#{#"id":#3},#{#"id":#4}];
NSArray *arr2 = #[#3,#1,#4,#2];
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (NSDictionary *item in arr1) {
map[item[#"id"]] = item;
}
NSMutableArray *arr3 = [NSMutableArray array];
for (id key in arr2) {
[arr3 addObject:map[key]];
}
This solution of course assumes parity between the two arrays. If arr2 has an element not in arr1 it will crash when trying to add nil to arr3. If arr1 has a value not in arr2 it will be excluded from arr3. These are risks you will have to address based on your requirements.
Here is how you can do it by using a custom comparator:
NSArray* sorted= [arr1 sortedArrayUsingComparator: ^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
return [arr2 indexOfObject:obj1[#"id"]] - [arr2 indexOfObject:[obj2[#"id"]];
}];
I exploited the fact that NSComparisonResult has +1 to represent an ascending order, -1 for descending and 0 to represent the same order.
- (NSArray*) sortedArray
{
NSArray *arr1 = #[#{#"id":#1},#{#"id":#2},#{#"id":#3},#{#"id":#4}];
NSArray *arr2 = #[#3,#1,#4,#2];
NSMutableArray *mutableArray = [NSMutableArray new];
for (NSNumber *number in arr2)
{
for (NSDictionary* dictionary in arr1)
{
NSNumber *number2 = dictionary[#"id"];
if ([number isEqual:number2])
{
[mutableArray addObject:dictionary];
break;
}
}
}
return mutableArray;
}

Resources