get distinct value from NSmutablearray [duplicate] - ios

This question already has answers here:
The best way to remove duplicate values from NSMutableArray in Objective-C?
(14 answers)
Closed 9 years ago.
i have a nsmutablearray as is shown below. I would like to retrieve list value without redundancy. in this example i should retrive 10 20 30
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:#"10",#"20",#"30",#"30",#"30",#"30",#"20", nil];

Transform the array into a set, and then back into an array.
NSSet *set = [NSSet setWithArray:array];
NSArray *a = [set allObjects];
You can also have this new array sorted:
NSArray *a2 = [a sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}];
Since iOS 5 you can use -[NSOrderedSet orderedSetWithArray:] which preserves the order:
NSArray *a2 = [[NSOrderedSet orderedSetWithArray:array] array];

NSArray *withRedunecy = [[NSSet setWithArray: array] allObjects];
This will be the one way like you can create new NSArray which has no duplicate objects or you need to create a logic for getting unique objects like insert one by one with checking is it already present or not.

Try to use this on
NSArray *array = #[#"10",#"20",#"30",#"30",#"30",#"30",#"20"];
NSArray *newArray = [[NSSet setWithArray:array] allObjects];
NSLog(#"%#", newArray);
Output :
(
30,
20,
10
)

Only this line of code will work fine .
NSSet *mySet = [NSSet setWithArray:array];
now mySet will have unique elements.so create array with this set
NSArray *myarray = [mySet allObjects];

Related

Sort an NsmutableDictionary Alphabetically [duplicate]

This question already has answers here:
sort NSDictionary values by key alphabetical order
(4 answers)
Closed 6 years ago.
I have a dictionary in which, for a single key(for example key "0") there are a key value pair data.The keys are like name, id,p_id. I want to sort the NSMutableDictionary for the values related to the Key "name". The data in the dictionary is as follows,
0 = {
id = 12;
name = "Accounts ";
"p_id" = 13222071;
};
1 = {
id = 13;
name = "consultant";
"p_id" = 15121211;
};
2 = {
id = 11;
name = "Tania";
"p_id" = 10215921;
};
}
Any help is appreciated!
Please try out the below code:
[yourMutableArray sortUsingComparator: (NSComparator)^(NSDictionary *a, NSDictionary *b) {
NSString *key1 = [a objectForKey: #"name"];
NSString *key2 = [b objectForKey: #"name"];
return [key1 compare: key2];
}];
NSLog(#"Sorted Array By name key : %#", yourMutableArray);
Hope this helps!
NSArray *sortedKeys = [dict.allKeys sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *d1, NSDictionary *d2) {
return [d1[#"name"] compare:d2[#"name"]];
}];
NSArray *objects = [dict objectsForKeys:sortedKeys notFoundMarker:[NSNull null]];
Dictionaries are not sorted, and doesn't resemble any order. What you should do is to getAll the keys first. Then apply a sort method on the keys, then request the objects according to the ordered keys.
E.g:
NSArray *keys = [dictionary allKeys];
NSArray *sortedKeys = <sort the keys according to your preferred method>
Now you can iterate the Dictionary from the order of the array sortedKeys.
While it has been made abundantly clear that Dictionaries can't be sorted and rightfully so, that does not mean the ends you are aiming for can't be achieved. This code will do that for you:
NSArray *arrayOfDicts = dic.allValues; //Now we got all the values. Each value itself is a dictionary so what we get here is an array of dictionaries
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES]; //Create sort descriptor for key name
NSArray *sortingDesc = [NSArray arrayWithObject:nameDescriptor];
NSArray *sortedArray = [arrayOfDicts sortedArrayUsingDescriptors:sortingDesc]; //Get sorted array based on name
NSMutableDictionary *kindaSortedDict = [[NSMutableDictionary alloc] init];
int keyForDict=0;
for(NSDictionary *valDict in sortedArray)
{
[kindaSortedDict setObject:valDict forKey:[NSString stringWithFormat:#"%i",keyForDict]]; //Set values to our new dic which will be kind of sorted as the keys will be assigned to right objects
keyForDict++;
}
//Now you can simply get sorted array of keys from kindaSortedDic and results for them will always be sorted alphabetically. Alternatively you can just skip all that bother and directly use sortedArray
I have added comments in code to help you understand that.
For accessing sorted values I'd do this:
NSArray *sortedKeys = [kindaSortedDict.allKeys sortedArrayUsingDescriptors:
#[[NSSortDescriptor sortDescriptorWithKey:#"intValue"
ascending:YES]]];
for(NSString *key in sortedKeys)
{
NSDictionary *valDict = [kindaSortedDict objectForKey: key];
NSLog(#"Dict is: %# for key: %#",valDict,key);
}

Remove duplicates from large NSMutableArray

I have a large mutable array with lots of duplicate values in alphabetical order.
I need to be able to convert my array *Array into a new array that contains one entry for each string variant.
I am currently using:
NSArray *array = [NSArray arrayWithObjects:papersObject.paperSubject, nil];
NSCountedSet *paperSet = [[NSCountedSet alloc] initWithArray:array];
NSMutableArray *namesArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
[namesSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop){
if ([paperSet countForObject:obj] == 1) {
[namesArray addObject:obj];
}
}];
NSLog(#"%#", namesArray);
But this returns a long list of the same array, still with duplicates.
Any ideas?
What about:
NSArray *arrayWithNoDuplicates = [[NSSet setWithArray:papersObject.paperSubject] allObjects];
A. What is namesSet? paperSet?
B. However:
NSOrderedSet *set = [NSOrderedSet orderedSetWithArray:array];
NSArray *arrayWithUniquesIsAnOrderedSet = set.array;
BTW: I would highly recommend to use an ordered set instead of an array, because an array with unique objects is an ordered set.

Join objects in sub-array into one array - Objective-c

Is there a one-liner to do the following
NSMutableArray *allpoints = [[NSMutableArray alloc] init];
for (NSMutableArray *arr in self.points)
[allpoints addObjectsFromArray:arr];
I have an array of arrays (self.points) and I am joining all of the objects in the subarrays into a single array.
NSArray *array1 = #[ #"a", #"b", #"c" ];
NSArray *array2 = #[ #"d", #"e", #"f" ];
NSArray *array3 = #[ array1, array2 ];
NSArray * flattenedArray = [array3 valueForKeyPath:#"#unionOfArrays.self"];
NSLog(#"flattenedArray: %#", flattenedArray);
Output:
flattenedArray: (
a,
b,
c,
d,
e,
f
)
There is not a way to add all objects in an array of arrays (e.g., every NSMutableArray in self.points to another array without iterating through.
However, you could add a category to NSArray to do exactly what you're doing now, and then call it with one line later.
If you are initializing the array and adding objects at the same time then there is an initializer for that.
NSMutableArray *allpoints = [[NSMutableArray alloc] initWithArray:self.points];
If you already have the mutable array defined and you want to just append objects to the end then you can use the following.
[allpoints addObjectsFromArray:self.points];
I don't think there is a way to do this.
NSMutableArray *allpoints = [[NSMutableArray alloc] initWithArray:self.points]
would give you an array of the arrays, but there is no single line solution. I'd suggest writing a category that will do this for you so you can easily reuse it.

Compare 2 arrays of strings

I got 2 arrays of strings:
NSArray * current = #[#"1", #"6", #"53"];
NSArray * new = #[#"1", #"626", #"53", #"13"];
I want to get number 6 in array, and numbers 626 and 13 in second array
(I want data that is in first array but there is not in second, and conversely)
NSMutableSet * newSet = [NSMutableSet setWithArray:new];
[newSet minusSet:[NSSet setWithArray:current ]];
NSArray * result1 = [NSArray arrayWithSet:newSet];
NSArray * result2 = ?
I not get it, I know that is very simple question, but I have no ideas
Your code contains a lot of syntax errors.
Please post actual code, I understand the issue you are talking about, that's why I'm posting this answer. Please post questions with valid code, else you won't get proper answer (Only get downvotes)
Use the following code:
NSArray *current = #[#"1", #"6", #"53"];
NSArray *newArr = #[#"1", #"626", #"53", #"13"];
NSMutableSet *newSet = [NSMutableSet setWithArray:newArr];
[newSet minusSet:[NSSet setWithArray:current]];
NSArray * result1 = [NSArray arrayWithObjects:[newSet allObjects],nil];
// result 1 will have 626 and 13
newSet = [NSMutableSet setWithArray:current];
[newSet minusSet:[NSSet setWithArray:newArr]];
NSArray * result2 = [NSArray arrayWithObjects:[newSet allObjects],nil];
// result 2 will have 6
// Create arrays of the IDs only
NSArray *notiCloudIDs = [notiCloud valueForKey:#"id"];
NSArray *notiLocIDs = [notiLoc valueForKey:#"id"];
// Turn the arrays into sets and intersect the two sets
NSMutableSet *notiCloudIDsSet = [NSMutableSet setWithArray:notiCloudIDs];
NSMutableSet *notiLocIDsSet = [NSMutableSet setWithArray:notiLocIDs];
[notiCloudIDsSet intersectSet:notiLocIDsSet];
// The IDs that are now in notiCloudIDsSet have been present in both arrays
NSLog(#"Duplicate IDs: %#", notiCloudIDsSet);
This will give you the common elements in the two. You can then delete the common elements from array1.

sort an NSMutableArray that contains NSString objects [duplicate]

This question already has answers here:
How to sort a NSArray alphabetically?
(7 answers)
Closed 9 years ago.
I am new to objective-c, ios.
I'm trying to sort in alfabetic order a NSMutableArray called filteredList that contains objects of type NSString.
so if my mutable array contains : [Mary, Bill, John] I would like to have [Bill, Mary, John]
I did the following:
[filteredList sortUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
but I do not see any change. I did read and tried other solutions like compare: instead of localizedCaseInsensitiveCompare but still nothing.
Updated
NSArray *sortedArray =[unSortedArray sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];//unSortedArray is NSMutableArray
unSortedArray = [[NSMutableArray alloc]initWithArray:sortedArray];
I would do something like:
NSArray *sortedArray = [filteredList sortedArrayUsingComparator:^(NSString *str1, NSString *str2) {
return (NSComparisonResult)[str1 compare:str2];
}];
filteredList = [sortedArray mutableCopy];
Please refer the below code:-
filteredList = (NSMutableArray*)[filteredList sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];

Resources