简体   繁体   中英

Compare Two Array and mapping equal the objects

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.

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}];
    }
}

I did try using NSPredicate on this.

Given:

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;
}];

Result:

{
A =     (
            {
        A = 1234;
    },
            {
        A = 1234;
    }
);
B =     (
            {
        B = 1234;
    },
            {
        B = 1234;
    },
            {
        B = 1234;
    }
);
N =     (
            {
        N = 1234;
    }
);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM