Peer Mohamed Thabib Peer Mohamed Thabib - 6 months ago 8
Objective-C Question

What is the best way to get unique set of objects from an array in objective C

I have an array with list of model objects

model object has properties Name, Age, gender,
I have date as follows

user* user1.name = "Bob",
user1.age = "10",
user1.gender = "M",

user* user2.name = "Bob",
user2.age = "11",
user2.gender = "M",

user* user3.name = "Woz",
user3.age = "15",
user3.gender = "M",

user* user4.name = "Woz",
user4.age = "16",
user4.gender = "M",


Now I need to get the unique name and lesser age as result.

user* user1.name = "Bob",
user1.age = "10",
user1.gender = "M",

user* user3.name = "Woz",
user3.age = "15",
user3.gender = "M",


what would be the efficient way to derive the above result. Thanks In advance Any Hint or help would appreciated.

Answer

You can simply iterate the array looking for the youngest users, storing each one in a dictionary keyed by name. Once you have iterated the array simply get all of the dictionary values as an array;

-(NSArray*)getYoungestUniqueUsersFromArray:(NSArray*)users {

    NSMutableDictionary* youngestUsersDict = [NSMutableDictionary new];

    for (User* user in users) {
        User* currentUser = youngestUsersDict[user.name];
        if (currentUser == nil || user.age < currentUser.age) {
            youngestUsersDict[user.name]=user;
        }
    }

    NSArray* youngestUsers = [youngestUsersDict allValues];

    return youngestUsers;
}
Comments