Narayana Narayana - 3 months ago 7
iOS Question

Get unique years from array

I have array with below structure, i want get array of unique year from that array.

I have got required output using for loop but can any suggest better way to get required output.

[
{ date = "2015-12-19 11:56:51 +0000"; },
    { date = "2015-12-19 11:56:51 +0000"; },
    { date = "2015-12-19 11:56:52 +0000"; },
    { date = "2013-11-19 11:56:52 +0000"; },
{ date = "2013-09-20 11:56:52 +0000"; },
    { date = "2014-12-07 11:56:58 +0000"; },
    { date = "2015-12-19 11:57:03 +0000"; },
    { date = "2012-08-08 11:57:07 +0000"; },
    { date = "2010-08-19 11:57:20 +0000"; }
]


For above array output array should be
["2015", "2014", "2013", "2012", "2010"]

Here is code which i am using right now:

NSMutableSet *setDate = [NSMutableSet set];
for (NSDictionary *dicData in arrayDates) {
NSString *strDate = [[dicData valueForKeyPath:@"date"] substringToIndex:4];
// my date format always same so no issue with substring
[setDate addObject:strDate];
}

Answer

One way or the other you need to loop over array's elements. It could be a "for" loop, a "foreach" loop, or a enumerateObjectsUsingBlock:, but the loop is going to be there.

Since years are relatively small integers, one way of collecting the output is to use NSIndexSet. This set is very fast, and it is always sorted. Here is a solution that uses enumerateObjectsUsingBlock:

NSMutableIndexSet *res = [NSMutableIndexSet indexSet];
[myDates enumerateObjectsUsingBlock:^(id d, NSUInteger index, BOOL *stop){
    NSDateComponents *dc = [[NSCalendar currentCalendar] components:NSCalendarUnitYear fromDate:d];
    [res addIndex:[dc year]];
}];

Now res contains unique years from dates in your NSArray.