问题
I have a bunch of NSArrays filled with numbers. Is there anyway that I can somehow grab a specific number, specifically like:
Third highest number in array, or 24th highest number in array?
But I don't want to just grab the number, I also need a reference to the index it was in the array as well, if that can be retained in the process.
Thanks.
回答1:
Third highest number in array, or 24th highest number in array?
Create a temporary copy of the array and sort it ascending.
Get the number at index 3-1
or 24-1
.
I also need a reference to the index it was in the array as well
Now use indexOfObject:
or indexOfObjectIdenticalTo:
to get the actual index.
回答2:
Starting with the sorted numbers
array from my answer here Getting Top 10 Highest Numbers From Array? :
NSUInteger wanted = 24 or anything;
NSUInteger count = 0;
NSNumber* previous = nil;
for (NSDictionary* entry in numbers)
{
if ( wanted == 1 ) return entry;
if (previous == nil)
{
// first entry
previous = entry[@"number"];
++ count;
continue;
}
// same number? skip it.
if ( entry[@"number"] isEqualTo: previous ) continue;
// if we get here, we found a different number we may be interested in
++ count;
if ( count == wanted ) return entry;
}
// nothing found
return nil;
The result is a line in the numbers
array from the previous question. An array of the form @[ @"number" : @<number>, @"parent" : <source array> ]
.
来源:https://stackoverflow.com/questions/11177585/pick-out-specific-number-from-array