Merge two arrays while preserving the original array order
I've writing an application that requests data from an external source (Twitter), which is returned as an ordered array in chronological order:
External array
- Item A (Latest)
- Item B
- Item C
- Item D (Oldest)
I add these items to another array preserving the same order:
My array
- Item A (Latest)
- Item B
- Item C
- Item D (Oldest)
I then query the external source again and receive another array of new items, it looks like this:
New External array
- Item E (Latest)
- Item F
- Item G
- Item H
I add them to my array and get this:
My array
- Item A
- Item B
- Item C
- Item D (Oldest)
- Item E (Latest)
- Item F
- Item G
- Item H
The problem is that the external array data is sorted chronologically with the newest item first originally that was A, since doing an update that is now E. So you can see the ordering of the array is now wrong, what I need is:
My array
- Item E (Latest)
- Item F
- Item G
- Item H
- Item A
- Item B
- Item C
- Item D (Oldest)
My code currently looks something like this:
NSMutableArray *myArray = [[NSMutableArray alloc] init];
...
- (void)getDataFromExternalSource:(NSArray *)externalArray
{
for(NSDictionary *item in externalArray) {
开发者_如何学JAVA // Need loop so I can do some extra stuff here with each item object (not shown in this example.)
[myArray addObject: item];
}
}
NSArray *newArray = [externalArray arrayByAddingObjectsFromArray:myArray];
[myArray release];
myArray = [newArray mutableCopy];
Any reason not to do this?
Just use the new array as the first array and add the old items after.
NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:externalArray.count + myArray.count];
for(NSDictionary *item in externalArray) {
// Need loop so I can do some extra stuff here with each item object (not shown in this example.)
[newArray addObject: item];
}
[newArray addObjectsFromArray:myArray];
You should use the array as a stack, so the old items get pushed below the newer ones. You could achieve that by adding every element at the last position using [myArray addObject:newObject];
. You will have to iterate backwards in the original array in order to insert them from oldest to newest. You can achieve that by doing :
for(NSUInteger index = [newArray count] - 1; i == 0; i--)
{
NSDictionary*object = [newArray objectAtIndex:index];
[myArray addObject:object];
}
This way you will get the array you need
Cheers
精彩评论