我正在使用名为inputArray
的数组,就像这样。
(
{
"2016-01-21" = {
amount = 3978;
date = "2016-01-20 18:30:00 +0000";
"date-day" = 21;
"date-month" = Jan;
"date-year" = 16;
units = 780;
};
},
{
"2015-11-20" = {
amount = 7938;
date = "2015-11-19 18:30:00 +0000";
"date-day" = 20;
"date-month" = Nov;
"date-year" = 15;
units = 1380;
};
},
{
"2015-10-03" = {
amount = 13423;
date = "2015-10-02 18:30:00 +0000";
"date-day" = 03;
"date-month" = Oct;
"date-year" = 15;
units = 2211;
};
},
{
"2015-09-26" = {
amount = 4110;
date = "2015-09-25 18:30:00 +0000";
"date-day" = 26;
"date-month" = Sep;
"date-year" = 15;
units = 800;
};
},
{
"2015-08-03" = {
amount = 18300;
date = "2015-08-02 18:30:00 +0000";
"date-day" = 03;
"date-month" = Aug;
"date-year" = 15;
units = 2950;
};
},
)
从这个数组中,我必须获得最高金额的date-month
。在此示例中,索引5包含amount
值18300
和该索引Aug
的月份。
怎么做?
此外,我需要将该值存储到NSString
。此外,我需要根据数量值对此数组进行排序,并将其存储到新数组中。
答案 0 :(得分:0)
假设您想要的值是字典,并且您有一个数组,例如:
NSDictionary *dict1 = @{
@"date" : @"2016-01-21",
@"values" : @{
@"amount" : @3978,
@"date" : @"2016-01-20 18:30:00 +0000",
@"date-day" : @21,
@"date-month" : @"Jan",
@"date-year" : @16,
@"units" : @780
}
};
NSDictionary *dict2 = @{
@"date" : @"2015-11-20",
@"values" : @{
@"amount" : @7938,
@"date" : @"2015-11-19 18:30:00 +0000",
@"date-day" : @20,
@"date-month" : @"Nov",
@"date-year" : @15,
@"units" : @1380
}
};
NSDictionary *dict3 = @{
@"date" : @"2015-10-03",
@"values" : @{
@"amount" : @13423,
@"date" : @"2015-10-02 18:30:00 +0000",
@"date-day" : @3,
@"date-month" : @"Oct",
@"date-year" : @15,
@"units" : @2211
}
};
NSDictionary *dict4 = @{
@"date" : @"2015-09-26",
@"values" : @{
@"amount" : @4110,
@"date" : @"2015-09-25 18:30:00 +0000",
@"date-day" : @26,
@"date-month" : @"Sep",
@"date-year" : @15,
@"units" : @800
}
};
NSDictionary *dict5 = @{
@"date" : @"2015-08-03",
@"values" : @{
@"amount" : @18300,
@"date" : @"2015-08-02 18:30:00 +0000",
@"date-day" : @3,
@"date-month" : @"Aug",
@"date-year" : @15,
@"units" : @2950
}
};
NSArray *array = @[dict1, dict2, dict3, dict4, dict5];
您可以使用比较器对数组进行排序:
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSNumber *amount1 = obj1[@"values"][@"amount"];
NSNumber *amount2 = obj2[@"values"][@"amount"];
// Sort in descending order so highest number is first
return [amount2 compare:amount1];
}];
由于数组按降序排序,您可以从排序数组中获取第一个字典,并从中获取您想要的任何值
NSString *dateWithMax = sortedArray.firstObject[@"values"][@"date-month"];
NSLog(@"%@", dateWithMax);