这里我有两个数组,就像第一个数组一样,
[
"A",
"B",
"A",
"B",
"N",
"B"
]
第二个数组,
[
{
"A": "2,141.8"
},
{
"B": "2,141.8"
},
{
"A": "2,141.8"
},
{
"B": "2,376"
},
{
"N": "2,376"
},
{
"B": "2,376"
},
]
但我需要将第一个数组对象比较到第二个数组中,如果它等于我想要的Key
和object
值,
{
"A": [
{
"A": "2,141.8"
},
{
"A": "2,141.8"
}
],
"B": [
{
"B": "2,376"
},
{
"B": "2,376"
}
]
}
您能否建议我如何实现这一点,谢谢。
答案 0 :(得分:1)
这将有效。
NSArray *arr1 = [NSArray arrayWithObjects:@"A",@"B",@"A",@"B",@"N",@"B", nil];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:arr1];
NSArray *arr2 = [orderedSet array];
NSArray *arr3 = [NSArray arrayWithObjects:
@{@"A": @"2,141.8"},
@{@"B": @"2,141.8"},
@{@"A": @"2,141.8"},
@{@"B": @"2,376"},
@{@"N": @"2,376"},
@{@"B": @"2,376"}, nil];
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i = 0 ; i <= arr2.count - 1; i++) {
NSMutableArray *arr4 = [[NSMutableArray alloc] init];
for (int j = 0 ; j <= arr3.count - 1; j++) {
if ([[arr3 objectAtIndex:j] objectForKey:[arr2 objectAtIndex:i]]) {
[arr4 addObject:[arr3 objectAtIndex:j]];
}
}
if (arr4.count != 0) {
[arr addObject:@{[arr2 objectAtIndex:i]:arr4}];
}
}
答案 1 :(得分:0)
我确实尝试过使用NSPredicate。
NSArray *keys = @[@"A",@"B",@"A",@"B",@"N",@"B"];
NSArray *sample = @[@{@"A":@"1234"},@{@"B":@"1234"},@{@"N":@"1234"},@{@"B":@"1234"},@{@"A":@"1234"},@{@"B":@"1234"}];
获取不同的密钥
NSArray *distinctKeys = [keys valueForKeyPath:@"@distinctUnionOfObjects.self"];
__block NSMutableDictionary *result = [NSMutableDictionary new]; // declare container
通过枚举不同的键
使用谓词过滤数组[distinctKeys enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
// Assume that there wont be a nil value
NSPredicate *predicator = [NSPredicate predicateWithFormat:@"%K != nil",obj];
NSArray *filtered = [sample filteredArrayUsingPredicate:predicator];
result[obj] = filtered;
}];
{
A = (
{
A = 1234;
},
{
A = 1234;
}
);
B = (
{
B = 1234;
},
{
B = 1234;
},
{
B = 1234;
}
);
N = (
{
N = 1234;
}
);
}