How to Find Duplicate Values in Arrays?

前端 未结 3 1663
栀梦
栀梦 2021-01-13 02:36

I am working on SQLite and I have written a query which returns me two arrays ItemsArray and CustomersIDArray as:

ItemsArray
Element at Index 0 = Off White,
         


        
相关标签:
3条回答
  • 2021-01-13 03:14

    Use NSCountedSet like below

    NSMutableArray *ary_res = [[NSMutableArray alloc] init];
        NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:@"11",@"13",@"34",@"9",@"13",@"34",@"9",@"2",nil];
        NSCountedSet *set = [[NSCountedSet alloc] initWithArray:array];
        for(id name in set)
        {
            if([set countForObject:name]==2)
                [ary_res addObject:name];
        }
        //
        NSLog(@"%@",ary_res);
    
    0 讨论(0)
  • 2021-01-13 03:21
    -(NSMutableArray *)getCountAndRemoveMultiples:(NSMutableArray *)array{
    
        NSMutableArray *newArray = [[NSMutableArray alloc]initWithArray:(NSArray *)array];
        NSMutableArray *countArray = [NSMutableArray new];
        int countInt = 1;
        for (int i = 0; i < newArray.count; ++i) {
            NSString *string = [newArray objectAtIndex:i];
            for (int j = i+1; j < newArray.count; ++j) {
                if ([string isEqualToString:[newArray objectAtIndex:j]]) {
                    [newArray removeObjectAtIndex:j];
                    countInt++;
                }
            }
            [countArray addObject:[NSNumber numberWithInt:countInt]];
            countInt = 1;
        }
        NSMutableArray *finalArray = [[NSMutableArray alloc] initWithObjects:newArray, countArray, nil];
        NSLog(@"%@", finalArray);
        return finalArray;
    
    }
    - (IBAction)getArrayInfo:(id)sender {
        NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:@"Off White", @"Fan", @"Off White", @"Deluxe", @"Fan", nil];
        NSMutableArray *godArray = [self getCountAndRemoveMultiples:myArray];
        NSLog(@"Array from this end = %@", godArray);
    }
    

    I just set up -getArrayInfo to test it out. Works fine. As you can see, the array you want to display will be at index:0, and the countArray at index:1.

    0 讨论(0)
  • 2021-01-13 03:28

    try this:

    NSArray *copy = [ItemsArray copy];
    
    NSInteger index = [copy count] - 1;
    
    for (id object in [copy reverseObjectEnumerator]) {
    
        if ([ItemsArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) {
            [ItemsArray removeObjectAtIndex:index];
        }
        index--;
    }
    
    0 讨论(0)
提交回复
热议问题