Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order two NSMutableArrays based on one

I have two NSMutableArrays. The content of the first is numerically, which is paired to the content of the second one:

First Array    Second Array
   45              Test45
   3               Test3
   1               Test1
   10              Test10
   20              Test20

That's the look of both arrays. Now how could I order them so numerically so they end up like:

First Array    Second Array
   1               Test1
   3               Test3
   10              Test10
   20              Test20
   45              Test45

Thanks!

like image 283
pmerino Avatar asked Dec 31 '11 13:12

pmerino


Video Answer


2 Answers

I would put the two arrays into a dictionary as keys and values. Then you can sort the first array (acting as keys in the dictionary) and quickly access the dictionary's values in the same order. Note that this will only work if the objects in the first array support NSCopying because that's how NSDictionary works.

The following code should do it. It's actually quite short because NSDictionary offers some nice convenience methods.

// Put the two arrays into a dictionary as keys and values
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:secondArray forKeys:firstArray];
// Sort the first array
NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
// Sort the second array based on the sorted first array
NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
like image 63
Ole Begemann Avatar answered Oct 18 '22 13:10

Ole Begemann


Rather than keep two parallel arrays, I'd keep a single array of model objects. Each number from the first array would be the value of one property, and each string from the second array would be the value of the other property. You could then sort on either or both properties using sort descriptors.

Generally, in Cocoa and Cocoa Touch, parallel arrays make work while model objects save work. Prefer the latter over the former wherever you can.

like image 36
Peter Hosey Avatar answered Oct 18 '22 14:10

Peter Hosey