按月份对 NSDictionary 的值进行分组和求和,其中键为 NSDate
Group and sum values of NSDictionary by month where key is NSDate
我有一个结构如下的字典,
arrayOne = {
"2015-11-09T00:00:00.000Z" = 1;
"2015-11-16T00:00:00.000Z" = 2;
"2015-11-23T00:00:00.000Z" = 3;
"2015-11-30T00:00:00.000Z" = 4;
"2015-12-07T00:00:00.000Z" = 5;
"2015-12-14T00:00:00.000Z" = 6;
"2015-12-21T00:00:00.000Z" = 7;
"2015-12-28T00:00:00.000Z" = 8;
"2016-01-04T00:00:00.000Z" = 9;
"2016-01-11T00:00:00.000Z" = 1;
"2016-01-18T00:00:00.000Z" = 2;
"2016-01-25T00:00:00.000Z" = 3;
}
我想创建另一个字典,其值如下,
arrayTWo = {
"November" = 10;
"December" = 26;
"January" = 15;
}
我尝试通过在单独的数组中获取日期的月份值和在单独的数组中获取值,然后尝试在 nsmutabledictionary 中获取这些值,但它不会为重复的键分配值并得到类似[=13的解决方案=]
arrayTWo = {
"November" = 4;
"December" = 8;
"January" = 3;
}
我找不到更好的方法,欢迎提供任何选项。谢谢
试试这个,它使用 NSDateFormatter
从日期中获取月份名称,它根据当前语言环境进行了本地化。如果您的语言环境不是英语并且您需要获取英语月份名称,请取消注释以明确设置语言环境。
逻辑很简单:
枚举字典,如果键(月)存在,则添加值,如果不创建键
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MMMM";
// formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDate *key in arrayOne.allKeys) {
NSString *month = [formatter stringFromDate:key];
if (result[month] == nil) {
result[month] = arrayOne[key];
} else {
NSInteger value = [result[month] integerValue];
result[month] = @(value + [arrayOne[key] integerValue]);
}
}
NSLog(@"%@", result);
我有一个结构如下的字典,
arrayOne = {
"2015-11-09T00:00:00.000Z" = 1;
"2015-11-16T00:00:00.000Z" = 2;
"2015-11-23T00:00:00.000Z" = 3;
"2015-11-30T00:00:00.000Z" = 4;
"2015-12-07T00:00:00.000Z" = 5;
"2015-12-14T00:00:00.000Z" = 6;
"2015-12-21T00:00:00.000Z" = 7;
"2015-12-28T00:00:00.000Z" = 8;
"2016-01-04T00:00:00.000Z" = 9;
"2016-01-11T00:00:00.000Z" = 1;
"2016-01-18T00:00:00.000Z" = 2;
"2016-01-25T00:00:00.000Z" = 3;
}
我想创建另一个字典,其值如下,
arrayTWo = {
"November" = 10;
"December" = 26;
"January" = 15;
}
我尝试通过在单独的数组中获取日期的月份值和在单独的数组中获取值,然后尝试在 nsmutabledictionary 中获取这些值,但它不会为重复的键分配值并得到类似[=13的解决方案=]
arrayTWo = {
"November" = 4;
"December" = 8;
"January" = 3;
}
我找不到更好的方法,欢迎提供任何选项。谢谢
试试这个,它使用 NSDateFormatter
从日期中获取月份名称,它根据当前语言环境进行了本地化。如果您的语言环境不是英语并且您需要获取英语月份名称,请取消注释以明确设置语言环境。
逻辑很简单:
枚举字典,如果键(月)存在,则添加值,如果不创建键
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"MMMM";
// formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
NSMutableDictionary *result = [NSMutableDictionary dictionary];
for (NSDate *key in arrayOne.allKeys) {
NSString *month = [formatter stringFromDate:key];
if (result[month] == nil) {
result[month] = arrayOne[key];
} else {
NSInteger value = [result[month] integerValue];
result[month] = @(value + [arrayOne[key] integerValue]);
}
}
NSLog(@"%@", result);