Reputation: 556
Here i have two array's like first array is,
[
"A",
"B",
"A",
"B",
"N",
"B"
]
second array like,
[
{
"A": "2,141.8"
},
{
"B": "2,141.8"
},
{
"A": "2,141.8"
},
{
"B": "2,376"
},
{
"N": "2,376"
},
{
"B": "2,376"
},
]
But i need to compare first array objects into the second array,if it is equal to both Key
and object
values i want like this,
{
"A": [
{
"A": "2,141.8"
},
{
"A": "2,141.8"
}
],
"B": [
{
"B": "2,376"
},
{
"B": "2,376"
}
]
}
Can you please suggest me how can i implement this,Thank you.
Upvotes: 2
Views: 251
Reputation: 2451
I did try using NSPredicate on this.
NSArray *keys = @[@"A",@"B",@"A",@"B",@"N",@"B"];
NSArray *sample = @[@{@"A":@"1234"},@{@"B":@"1234"},@{@"N":@"1234"},@{@"B":@"1234"},@{@"A":@"1234"},@{@"B":@"1234"}];
Get the distinct keys
NSArray *distinctKeys = [keys valueForKeyPath:@"@distinctUnionOfObjects.self"];
__block NSMutableDictionary *result = [NSMutableDictionary new]; // declare container
Filter the array using predicate by enumerating the distinct keys
[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;
}
);
}
Upvotes: 0
Reputation: 1265
this will work.
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}];
}
}
Upvotes: 1