Sort 2 arrays? Objective-c [duplicate] - objective-c

I have several arrays that need to be sorted side by side.
For example, the first array has names: #[#"Joe", #"Anna", #"Michael", #"Kim"], and
and the other array holds addresses: #[#"Hollywood bld", #"Some street 3", #"That other street", #"country road"], where the arrays' indexes go together. "Joe" lives at "Hollywood bld" and so on.
I would like to sort the names array alphabetically, and then have the address array sorted alongside so they still go together, with "Hollywood bld" having same index as "Joe". I know how to sort one array alphabetical with
NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];
But is there any easy way of getting the second array sorted using the appropriate order?

Create a permutation array, initially set to p[i]=i
Sort the permutation according to the name key of the first array
Use the permutation to re-order both arrays
Example: let's say the first array is {"quick", "brown", "fox"}. The permutation starts as {0, 1, 2}, and becomes {1, 2, 0} after the sort. Now you can go through the permutation array, and re-order the original array and the second array as needed.
NSArray *first = [NSArray arrayWithObjects: #"quick", #"brown", #"fox", #"jumps", nil];
NSArray *second = [NSArray arrayWithObjects: #"jack", #"loves", #"my", #"sphinx", nil];
NSMutableArray *p = [NSMutableArray arrayWithCapacity:first.count];
for (NSUInteger i = 0 ; i != first.count ; i++) {
[p addObject:[NSNumber numberWithInteger:i]];
}
[p sortWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
// Modify this to use [first objectAtIndex:[obj1 intValue]].name property
NSString *lhs = [first objectAtIndex:[obj1 intValue]];
// Same goes for the next line: use the name
NSString *rhs = [first objectAtIndex:[obj2 intValue]];
return [lhs compare:rhs];
}];
NSMutableArray *sortedFirst = [NSMutableArray arrayWithCapacity:first.count];
NSMutableArray *sortedSecond = [NSMutableArray arrayWithCapacity:first.count];
[p enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSUInteger pos = [obj intValue];
[sortedFirst addObject:[first objectAtIndex:pos]];
[sortedSecond addObject:[second objectAtIndex:pos]];
}];
NSLog(#"%#", sortedFirst);
NSLog(#"%#", sortedSecond);

First off, you might want to re-consider an architecture that requires you to sort two arrays in a parallel fashion like this. But having said that, you can do it by creating a temporary array of dictionaries that keep the elements of the two arrays paired.
Then you sort the combined array, and extract the two arrays again, sorted as requested:
Original data:
NSArray *names = #[#"Joe", #"Anna", #"Michael"];
NSArray *addresses = #[#"Hollywood bld", #"Some street 3", #"That other street"];
The actual sorting code:
NSMutableArray *combined = [NSMutableArray array];
for (NSUInteger i = 0; i < names.count; i++) {
[combined addObject: #{#"name" : names[i], #"address": addresses[i]}];
}
[combined sortUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"name" ascending:YES]]];
names = [combined valueForKey:#"name"];
addresses = [combined valueForKey:#"address"];
Notice that valueForKey: used on an array extracts a new array with the same size, populated with the properties of the objects in the original array. In this case, it create new arrays from the original ones, sorted as wanted.
This approach only requires a few lines of code and is easy to follow and debug, if needed.

The best way is to restructure your data so that you only have one array. In your example, it would make most sense to create a new class with both name and address, put those in an array and sort it by name.

You could probably do this by keeping track of indexes of objects before and after the sort but maybe it would be easier having a single object which hass all of these properties
Person : NSObject
#property (nonatomic, copy) NSString *name;
#property (nonatomic, copy) NSString *addresss;
Then you store these objects into a single array which you can sort by name, or address key paths

Related

How to sort an NSArray with nested NSArray

I have an instance of NSArray with instances of NSArray inside. The inner arrays contain only instances of NSString. I need to sort the nested arrays alphabetically by a selected index.
E.g.
#[
#[#"test",#"B",#"test2"],
#[#"bla",#"A",#"bla"],
#[#"xyz",#"C",#"123"]
]
User selects index 1, Ascending sort. Result should be:
#[
#[#"bla",#"A",#"bla"],
#[#"test",#"B",#"test2"],
#[#"xyz",#"C",#"123"]
]
You can use sortedArrayUsingComparator:
NSArray *array = #[#[#"test",#"B",#"test2"],
#[#"bla",#"A",#"bla"],
#[#"xyz",#"C",#"123"]];
NSInteger index = 1;
NSArray *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
return [obj1[index] compare:obj2[index] options:NSCaseInsensitiveSearch];
}];
Clearly, if the subarrays have different number of items or if they're not all strings, you might include some additional logic to handle that, but it illustrates the basic idea.

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

obj-c fetching strings from array

i'm new to obj-c (this is my first day class eheh) and i'm trying to change a label with a random string from a multidimensional array. plus, every time the button is hitten you switch the array. i know it's a bit odd eheh… this is the IBAction:
UIButton *button = (UIButton *)sender;
NSMutableArray *firstArray = [NSMutableArray array];
[firstArray addObject:#"foo"];
NSMutableArray *secondArray = [NSMutableArray array];
[secondArray addObject:#"bar"];
NSMutableArray *frasi = [NSMutableArray array];
[frasi addObject:firstArray];
[frasi addObject:secondArray];
NSMutableArray *array = [NSMutableArray arrayWithObjects:[frasi objectAtIndex:[button isSelected]], nil];
NSString *q = [array objectAtIndex: (arc4random()% [array count] )];
NSString *lab = [NSString stringWithFormat:#"%#", q];
self.label.text = lab;
all works, but the new label is
( "foo" )
instead of just foo (without quotes)... probably i mess in the last block of code...
ty
So, you create 2 mutable arrays, then add them to a new mutable array frasi. Then you get one of those two arrays and use it as the single element (because you use arrayWithObjects: instead of arrayWithArray:) of a new array array.
So array is an array that contains a single array element (instead of an array of strings as you may believe).
When you get an object from array, it's always the same single object that was used to initialize it: either firstArray or secondArray.
So you get an array of strings where you expect a string. When using stringWithFormat:, the specifier %# is replaced with the string description of that object.
A string returns itself as its own description. But the description of an array is the list of all its elements separated with commas and surrounded by parenthesis, which is why you get ( "foo" ).
So instead or creating unneeded arrays, you may just replace all the 8th last lines with this:
NSArray *array = [button isSelected] ? secondArray : firstArray;
self.label.text = [array objectAtIndex:arc4_uniform([array count])];
Actually u have array within array
Replace this line with yours:
NSString *q = [[array objectAtIndex: (arc4random()% [array count] )] objectAtIndex:0];

Creating an NSDictionary from an NSArray (Objective-c 2.0)

I have an NSArray containing n elements at indices 0, 1 ... n-1. I want to populate an NSDictionary with the contents of my array.
Specifically the dictionary should contain key-value pairs where the key is the hash of the ith element in the array and the value is the index into the array.
For example: array = [123, 101, 199] then the dictionary will contain three key-value pairs:
([123 hash], 0)
([199 hash], 2)
([101 hash], 1)
I've done this with a for loop over the array. What's a more concise way to do this? Perhaps something from NSKeyValueCoding?
More info: I'm thinking of something like this:
NSArray *keys = [myArray valueForKey:#"hash"];
NSArray *values = [myArray valueForKey:#"index"]; // #"index" needs to change
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:values
forKeys:keys];
I would probably use something like David's for loop solution myself, but just for kicks, and because I'm still trying to wrap my head completely around them, I came up with a solution using blocks:
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:[array count]];
[array enumerateObjectsUsingBlock:^ (id obj, NSUInteger idx, BOOL *stop) {
[dict setObject:[NSNumber numberWithUnsignedLong:idx] forKey:hashFor(obj)]; } ];
I'm assuming the existence of a function hashFor that generates the hash. You can replace that part with a message to obj or whatever you do to generate the hash.
A for loop is pretty good, especially if you need the index. Otherwise you might use fast enumeration:
int i = 0;
for (object in array) {
… [NSNumber numberWithInt: i] … // Add to dict
i++;
}
This has nothing to do with KVC.

Sorting NSDictionary

I was wondering if someone can show me how to sort an NSDictionary; I want to read it starting from the last entry, since the key is Date + Time and I want to be able to append it to an NSMutableString. I was able to read it using an enumerator but I don't get the results I want.
Thanks
For your requirements the easiest way is to create a new array from the keys, sort that, then use the array to reference items from the original dictionary.
(Note myComparison is your own method that will compare two keys).
NSMutableArray* tempArray = [NSMutableArray arrayWithArray:[myDict allKeys]];
[tempArray sortedArrayUsingSelector:#selector(myComparison:)];
for (Foo* f in tempArray)
{
Value* val = [myDict objectForKey:f];
}
I've aggregated some of the other suggestions on StackOverflow on sorting an NSDictionary into something very compact that will sort alphabetically. I have a Plist file in 'path' that I load in to memory and want to dump.
NSDictionary *glossary = [NSDictionary dictionaryWithContentsOfFile: path];
NSArray *array1 = [[glossary allKeys] sortedArrayUsingDescriptors:#[ [NSSortDescriptor sortDescriptorWithKey:#"" ascending:YES selector:#selector(localizedStandardCompare:)] ]];
for ( int i=0; i<array1.count; i++)
{
NSString* key = [array1 objectAtIndex:i];
NSString* value = [glossary objectForKey:key];
NSLog(#"Key=%#, Value=%#", key, value );
}