Reputation: 59
I have what I think is an interesting question. I have two arrays which I need to merge and sort. Each array is an array of dictionary objects, but the structure of each dictionary object is different. So one array contains elements that each contain a list of, say, 12 keys/values. The other array has elements that contain a list of, say 15 keys/values. Some of the keys/values might be the same, but not necessarily in the same order, and not necessarily formatted the same (e.g., the date field is formatted differently in each array).
What I need to do (eventually) is combine them, and sort on one common key - the date field.
I don't think an array can have elements with different structures across individual elements, can it? I've never used a language that will do this, although I ask because I wouldn't be surprised if objective-c could.
Anyway, I have been reading Apple's documentation, and there are a lot of great sorting and merging algorithms already provided. But I could use some help deciding on what approach to use.
The fact is, I only need about 5 fields, so I feel like I want to create a third array of dictionaries with the structure I want, and then transfer all items into it, then sort after. But where do I start?
If anyone has any experience with this I'd appreciate some guidance.
Upvotes: 1
Views: 1871
Reputation: 5966
In Objective-C you can have an NSArray with any type of object in it.Structure,that consists only of NSArrays, NSSets and NSDictionaries is called Collection.
So you can merge them into one and easily sort it by date
So, after merge,you could sort your array like this
NSSortDescriptor *sortByDateDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date"
ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortByDateDescriptor];
NSArray *sortedArray = [mergedArray sortedArrayUsingDescriptors:sortDescriptors];
To merge to NSMutableArray's,just use [firstrray addObjectsFromArray: secondArray];
Upvotes: 1