Search code examples
iosarrayssetnsarraynsset

Create an array of NSSet having values of distinct properties of an object present in another NSArray


I have an array having objects with different properties. I want to create an array of sets which contain objects with same value of a single property of the object.

Suppose this is an array of object which has property a and b

1: {a:10, b:5}, 2: {a:2,b:5}, 3: {a:20,b:5}, 4: {a:5,b:5}, 5: {a:4,b:20}, 6: {a:51,b:20}

I want to create another array of NSSet of objects with distinct values of property b

so the result would be the following Array of 2 NSSet

1: {a:10, b:5}, {a:2,b:5}, {a:20,b:5}, {a:5,b:5}

2: {a:4,b:20}, {a:51,b:20}

How can this be done?


Solution

  • I'd do this by first creating a dictionary of sets where the keys of the dictionary are the unique values of "b".

    Note: This is untested code. There could be typos here.

    NSArray *objectArray = ... // The array of "SomeObject" with the "a" and "b" values;
    NSMutableDictionary *data = [NSMutableDictionary dictionary];
    for (SomeObject *object in objectArray) {
        id b = object.b;
        NSMutableSet *bSet = data[b];
        if (!bSet) {
            bSet = [NSMutableSet set];
            data[b] = bSet;
        }
    
        [bSet addObject:object];
    }
    
    NSArray *setArray = [data allValues];
    

    setArray will contain your array of sets.

    This codes also assumes you have a sane isEqual: and hash implementation on your SomeObject class.