-1

I have NSarray contains the list of Animals. The array contains a list of animals with repeated elements. I have to make an array with distinct values in the array. Repeated values should be removed using NSPredicate.

Here is my Code :-

NSArray *arrAnimals = [[NSArray alloc] initWithObjects:@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog", nil];

NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"distinct"]];
arrAnimals = [arrAnimals filteredArrayUsingPredicate:predicate];

Here I am using "distinct" keyword for sorting the array, but not able to find any solution. I have preferred many links.

http://www.infragistics.com/community/blogs/stevez/archive/2013/10/21/ios-objective-c-filtering-a-nsarray-using-nspredicate.aspx

Please resolve my problem.

ChintaN -Maddy- Ramani
  • 5,156
  • 1
  • 27
  • 48
Apoorv
  • 39
  • 1
  • 11

3 Answers3

2

There is no predicate for this, but you can use Key-Value Operator:

distinct = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];
Tricertops
  • 8,492
  • 1
  • 39
  • 41
  • Thanks for the keyword "distinctUnionOfObjects.self". This method will also returns sorted array. After removing repeated values. – Apoorv Jul 07 '14 at 12:40
  • It preserves the order, so if your original array is sorted, the result will be too. – Tricertops Jul 07 '14 at 13:18
1

You can remove duplicates from an array by creating a set with its objects and converting it back to an array.

NSArray *arrAnimals = [[NSArray alloc] initWithObjects:@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog", nil];
NSArray *arrayWithoutDuplicates = [[NSSet setWithArray:arrAnimals] allObjects];
Adam
  • 26,549
  • 8
  • 62
  • 79
  • This code works for me. This will returns the array of after removing duplicate values, without using NSPredicate. Thanks – Apoorv Jul 07 '14 at 12:38
0

try this one with answered by @iMartin

 NSArray *arrAnimals = @[@"Cat",@"Rat",@"Fish",@"Cat",@"Fish",@"Cat",@"Cat",@"Bird",@"Fish",@"Cat",@"Frog"];

    arrAnimals= [arrAnimals valueForKeyPath:@"@distinctUnionOfObjects.self"];

    arrAnimals= [arrAnimals sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        unichar firstChar =  [obj1 characterAtIndex:0];
        unichar secondChar =  [obj2 characterAtIndex:0];

        if ( firstChar == secondChar) {
            return NSOrderedSame;
        } else {
            if ( firstChar > secondChar) {
                return NSOrderedDescending;
            } else {
                return NSOrderedAscending;
            }

        }

    }];
Jasmin
  • 794
  • 7
  • 18