I need to sort an array of age groups. The challenge is that any age groups less than 10 sort higher than those 10-19 when using the standard NSArray localizedCaseInsensitiveCompare
Specifically, here’s an example of what my unsorted array might look like:
(
“17-18”,
“13-14”,
“8 and Under”,
“Women”,
“Men”,
“15-16”
)
After sorting, I would want it to look like this:
(
“8 and Under”,
“13-14”,
“15-16”,
“17-18”,
“Men”,
“Women”
)
But it ends up looking something like this:
(
“13-14”,
“15-16”,
“17-18”,
“8 and Under”,
“Men”,
“Women”
)
This is using the following code:
NSArray *sortedAgeArray = [ageArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
I like that “Men” and “Women” gets put on the end, that’s what I want. But is there a clever/efficient way to deal with the ages that are less than 10? Reformatting my data to include leading zeroes is not an option.
I know I can write a custom sorting function, but I’m trying to avoid having to do so.
Thanks!
You could use
localizedStandardCompare:instead oflocalizedCaseInsensitiveCompare:. This is what the Finder uses and it’s smart enough to evaluate “8” as smaller than “13” without leading zeros.