BluGeni BluGeni - 1 day ago 5
iOS Question

loop through nsmutablearray and remove object that is duplicated

I have a NSMutableArray that looks like the one below and want to look through and remove the objects that have the same realLocationName and ADD_LINE1
and leave just the realLocationName object.

my array now:

(
{
locationId = "12-11-2013 10:23:53";
realLocationName = wauk;
},
{
locationId = "01-02-2014 10:10:11";
realLocationName = sdf;
},
{
locationId = "01-02-2014 11:55:49";
realLocationName = "514 COURT AVE";
},
{
"ADD_CITY" = city;
"ADD_LINE1" = "514 COURT AVE";
"ADD_LINE2" = "";
"ADD_STATE" = IA;
"ADD_ZIP" = 50833;
"BUSINESS_NAME" = "";
"FIRST_NAME" = joe;
"LAST_NAME" = smith;
},
{
"ADD_CITY" = cty2;
"ADD_LINE1" = "514 COURT AVE";
"ADD_LINE2" = "";
"ADD_STATE" = IA;
"ADD_ZIP" = 50833;
"BUSINESS_NAME" = "";
"FIRST_NAME" = randy;
"LAST_NAME" = red;
}
)


What I am trying to get:

(
{
locationId = "12-11-2013 10:23:53";
realLocationName = wauk;
},
{
locationId = "01-02-2014 10:10:11";
realLocationName = sdf;
},
{
locationId = "01-02-2014 11:55:49";
realLocationName = "514 COURT AVE";
}
)


EDIT:

or this scenario:
array =

(
{
locationId = "12-11-2013 10:23:53";
realLocationName = wauk;
},
{
locationId = "01-02-2014 10:10:11";
realLocationName = sdf;
},
{
"ADD_CITY" = city;
"ADD_LINE1" = "514 COURT AVE";
"ADD_LINE2" = "";
"ADD_STATE" = IA;
"ADD_ZIP" = 50833;
"BUSINESS_NAME" = "";
"FIRST_NAME" = joe;
"LAST_NAME" = smith;
},
{
"ADD_CITY" = cty2;
"ADD_LINE1" = "514 COURT AVE";
"ADD_LINE2" = "";
"ADD_STATE" = IA;
"ADD_ZIP" = 50833;
"BUSINESS_NAME" = "";
"FIRST_NAME" = randy;
"LAST_NAME" = red;
}
)


and get this:

(
{
locationId = "12-11-2013 10:23:53";
realLocationName = wauk;
},
{
locationId = "01-02-2014 10:10:11";
realLocationName = sdf;
},
{
"ADD_CITY" = city;
"ADD_LINE1" = "514 COURT AVE";
"ADD_LINE2" = "";
"ADD_STATE" = IA;
"ADD_ZIP" = 50833;
"BUSINESS_NAME" = "";
"FIRST_NAME" = joe;
"LAST_NAME" = smith;
}
)

nzs nzs
Answer

You can use a set (NSMutableSet) to check whether a realLocationName added or not.

How this code works?

1) every object, I get the value of "realLocationName" key or "ADD_LINE1" key assuming that no object has both of these keys but one key exists definitely

2) the array is ordered that all "realLocationName" objects are in the beginning part - this is because it was a requirement that object with realLocationName are preferred that object with ADD_LINE1.

NSMutableArray *arr_noduplicates = [NSMutableArray array];
NSMutableSet *set_of_already_added = [NSMutableSet set];

for (NSDictionary *obj in originalArray) {
    NSString *str_value = [NSString stringWithFormat:@"%@%@", 
                          obj[@"realLocationName"] ? obj[@"realLocationName"] : @"", 
                          obj[@"ADD_LINE1"] ? obj[@"ADD_LINE1"] : @""];
    if (![set_of_already_added containsObject:str_value]) {
        [arr_noduplicates addObject:obj];
        [set_of_already_added addObject:str_value];
    }
}
Comments