I have a NSArray of NSDictionary objects:
[
{
id = 1;
fromDate = 2014-04-03;
toDate = 2014-04-05;
date = 0000-00-00;
title = title 1
},
{
id = 1;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-04-03
title = title 1
},
{
id = 1;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-04-04;
title = title 1
},
{
id = 2;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-05-10;
title = title 2
},
{
id = 2;
fromDate = 0000-00-00;
toDate = 0000-00-00;
date = 2014-05-11;
title = title 2
}
]
I would like to merge dictionaries with same id value into one dictionary combining all date, fromDate and toDate keys, obtaining an array like this, that ignores zero values:
[
{
id = 1,
combinedDates = 2014-04-03, 2014-04-05, 2014-04-03, 2014-04-04;
title = title 1
},
{
id = 2,
combinedDates = 2014-05-10, 2014-05-11;
title = title 2
}
]
Can someone point me to the right direction?
I don't know of any way to do this other than basic brute force:
-(NSArray*)combinedArray:(NSArray*)array
{
NSMutableArray* combined = [NSMutableArray new];
// Iterate over each unique id value
for(id key in [NSSet setWithArray:[array valueForKeyPath:#"id"]])
{
// skip missing keys
if([key isKindOfClass:[NSNull class]])
continue;
// Sub array with only id = key
NSArray* filtered = [array filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(NSDictionary* evaluatedObject, NSDictionary *bindings) {
return [evaluatedObject valueForKey:#"date"] && [[evaluatedObject valueForKey:#"id"] isEqual:key];
}]];
// Grab the dates
NSArray* dates = [filtered valueForKeyPath:#"date"];
// add the new dictionary
[combined addObject:#{ #"id":key, #"combinedDates":dates }];
}
return array;
}
// Group By id
-(NSMutableDictionary*)combinedArray:(NSArray*)array
{
NSMutableArray *categories = [[NSMutableArray alloc] init];
for (NSDictionary *data in array) {
NSString *category = [data valueForKey:#"id"];
if (![categories containsObject:category]) {
[categories addObject:category];
}
}
NSMutableDictionary *categoryData = [[NSMutableDictionary alloc]init];
for (NSString *strCat in categories) {
NSMutableArray *catArray = [[NSMutableArray alloc]init];
for (NSDictionary *data in array) {
NSString *category = [data valueForKey:#"id"];
if ([category isEqualToString:strCat]) {
[catArray addObject:data];
}
}
[categoryData setObject:catArray forKey:strCat];
}
return categoryData;
}
Related
i have a NSDictionary like:
{
"2017-05-02" = (
{
"always_valid" = 0;
date = "2017-05-02";
from = "12:00";
to = "13:00";
},
{
"always_valid" = 0;
date = "2017-05-02";
from = "12:00";
to = "12:00";
},
{
"always_valid" = 0;
date = "2017-05-02";
from = "14:00";
"hourly_rate" = 12;
to = "15:00";
}
);
"2017-05-03" = (
{
"always_valid" = 0;
date = "2017-05-03";
from = "12:00";
to = "13:00";
}
);
"2017-05-18" = (
{
"always_valid" = 1;
date = "2017-05-18";
from = "12:00";
to = "12:00";
}
);
}
i'm trying to apply
NSPredicate *filter = [NSPredicate predicateWithFormat:#"always_valid = \"1\""];
NSArray *alwaysvalid = [[dic allValues] filteredArrayUsingPredicate:filter];
it use to work when i had structure something like
array > dictionary
but now it's like
array > array > dictionary
by doing [dic allValues] for array.
any help what should i apply to keep it fast.
What you need to do is need enumerate your dictionary and create new filtered Dictionary.
NSMutableDictionary *filterDic = [[NSMutableDictionary alloc] init];
NSPredicate *filter = [NSPredicate predicateWithFormat:#"always_valid = 1"];
[dict enumerateKeysAndObjectsUsingBlock:^(NSString* key, NSArray* obj, BOOL *stop) {
NSArray *filterArray = [obj filteredArrayUsingPredicate:filter];
if (filterArray.count > 0) {
filterDic[key] = filterArray;
}
}];
Try this :
NSArray *array = [NSArray arrayWithObject:dict]; // you can also do same for Name key...
NSArray *alwaysvalid = [array filteredArrayUsingPredicate:filter];
I have an array of dictionaries that I am trying to get the Max score for each player in the array. Each player can have multiple entries I am trying to get an array of dictionaries of each players best score.
NSArray
[0] - NSDictionary
- [0] Score: (double)20.7
- [1] NameID: (int) 1
- [2] Date
[1] - NSDictionary
- [0] Score: (double)25
- [1] NameID: (int) 1
- [2] Date
[2] - NSDictionary
- [0] Score: (double)28
- [1] NameID: (int) 2
- [2] Date
[3] - NSDictionary`
- [0] Score: (double)26
- [1] NameID: (int) 3
- [2] Date
I have tried using NSPredicate predicateWithFormat but I am only able to get back the max for everything in the array not related to the name.
Expected Output:
NSArray
[1] - NSDictionary
- [0] Score: (double)25
- [1] NameID: (int) 1
- [2] Date
[2] - NSDictionary
- [0] Score: (double)28
- [1] NameID: (int) 2
- [2] Date
[3] - NSDictionary`
- [0] Score: (double)26
- [1] NameID: (int) 3
- [2] Date
Thanks for the help.
You can't use an NSPredicate for this, since you want to determine the maximum score for several different players. Under the covers, NSPredicate iterates the array anyway, so using your own loop isn't any less efficient. In the following code I have assumed that the scores and player names are wrapped in NSNumber
-(NSArray *)maxScoresForPlayers:(NSArray *)playerScores {
NSMutableDictionary *maxScores = [NSMutableDictionary new];
for (NSDictionary *player in playerScores) {
NSNumber *playerID = (NSNumber *)player[#"NameID"];
NSDictionary *playerMax = maxScores[playerID];
if (playerMax == nil) {
playerMax = player;
} else {
NSNumber *currentMax = (NSNumber *)[playerMax[#"Score"];
NSNumber *playerScore = (NSNumber *)player[#"Score"];
if ([playerScore doubleValue] > [currentMax doubleValue]) {
playerMax = player;
}
}
maxScores[playerID] = playerMax;
}
return([maxScores allValues];
}
You can do it manually like this:
NSMutableDictionary *maxScoresDict = [NSMutableDictionary dictionary];
for (NSDictionary *score in scoresArray) {
NSNumber *key = score[#"NameID"];
NSNumber *savedMax = maxScoresDict[key][#"Score"];
NSNumber *currentMax = maxScoresDict[key][#"Score"];
if (savedMax == nil || [currentMax doubleValue] > [savedMax doubleValue]) {
maxScoresDict[key] = score;
}
}
NSArray *maxScoresArray = [maxScoresDict allValues];
Try this:
NSArray *objects = #[#{#"Score": #(20.7),
#"NameID": #(1),
#"Date": [NSDate date]},
#{#"Score": #(25),
#"NameID": #(1),
#"Date": [NSDate date]},
#{#"Score": #(28),
#"NameID": #(2),
#"Date": [NSDate date]},
#{#"Score": #(26),
#"NameID": #(3),
#"Date": [NSDate date]}];
NSMutableArray *users = [NSMutableArray array];
for (NSInteger i=0; i<objects.count; i++) {
NSDictionary *dict = objects[i];
NSNumber *nameID = dict[#"NameID"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"self.NameID==%#", nameID];
NSInteger index = [users indexOfObjectPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
BOOL found = [predicate evaluateWithObject:obj];
return found;
}];
if (index != NSNotFound) {
NSNumber *score1 = dict[#"Score"];
NSNumber *score2 = users[index][#"Score"];
if (score1.doubleValue > score2.doubleValue) {
[users replaceObjectAtIndex:index withObject:dict];
}
}
else {
[users addObject:dict];
}
}
NSLog(#"%#", users);
- (NSArray *)getBestScores:(NSArray *)players {
NSMutableDictionary *best = [[NSMutableDictionary alloc] init];
for (NSDictionary *p in players) {
NSDictionary *b = [best valueForKey:[p valueForKey:#"NameID"]];
if (!b || [[p valueForKey:#"Score"] doubleValue] > [[b valueForKey:#"Score"] doubleValue])
[best setValue:p forKey:[p valueForKey:#"NameID"]];
}
return [best allValues];
}
// Get Max Value of integer element from Array of Dictonaries.
// Example Array Starts
<paramArray>(
{
DicID = 1;
Name = "ABC";
ValuetoCalculateMax = 2800;
},
{
DicID = 2;
Name = "DEF";
ValuetoCalculateMax = 2801;
},
{
DicID = 3;
Name = "GHI";
ValuetoCalculateMax = 2805;
}
)
// Example Array Ends
// Implementation
int MaxintegerValue=0;
MaxintegerValue=[self getMaxValueFromArrayofDictonaries:paramArray];
// Implementation Ends
// Function Starts
-(int)getMaxValueFromArrayofDictonaries:(NSArray *)paramArray
{
int MaxValue=0;
NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
for ( int i=0; i<[paramArray count]; i++ )
{
dic=[paramArray objectAtIndex:i];
if ([[dic valueForKey:#"ValuetoCalculateMax"] intValue] > MaxValue)
{
MaxValue=[[dic valueForKey:#"ValuetoCalculateMax"] intValue];
}
else
{
MaxValue=MaxValue;
}
}
return MaxValue;
}
// Function Ends
What you need to do is find scores for each user, then find the max score out of it.
- (void)findMaxScoreForUser:(int)userId {
NSDictionary *dict0 = [NSDictionary dictionaryWithObjects:#[#27.0,#3] forKeys:#[#"Score",#"UserID"]];
NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:#[#25.0,#2] forKeys:#[#"Score",#"UserID"]];
NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:#[#23.0,#3] forKeys:#[#"Score",#"UserID"]];
NSArray *arr = [NSArray arrayWithObjects:dict0,dict1,dict2, nil];
NSMutableArray *scores = [NSMutableArray array];
for (NSDictionary *dict in arr) {
int userID = [[dict valueForKey:#"UserID"] intValue];
if (userId == userID) {
[scores addObject:[dict valueForKey:#"Score"]];
}
}
int max = [[scores valueForKeyPath:#"#max.intValue"] intValue];
}
Hi This is what am getting from server
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
4 = {
"display_name" = "ffd";
id = 4;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
}
i need to sort this based on "id" this is what am looking as output
Expecting output
{
1 = {
"display_name" = "One";
id = 1;
};
2 = {
"display_name" = "Two";
id = 2;
};
3 = {
"display_name" = "abdfdfc";
id = 3;
};
4 = {
"display_name" = "ffd";
id = 4;
};
5 = {
"display_name" = "aasdfsdfa";
id = 5;
};
13 = {
"display_name" = "abc";
id = 13;
};
15 = {
"display_name" = "aaa";
id = 15;
};
}
This code i have tried and its not working
//vehiclesDictionary real dictionary
NSMutableArray *sortedKeys=[[NSMutableArray alloc]init];
for(NSString *item in [vehiclesDictionary allKeys]){
[sortedKeys addObject:[NSNumber numberWithInt:[item intValue]]];
}
NSArray *sortedKeysArray = [sortedKeys sortedArrayUsingSelector: #selector(compare:)];
NSLog(#"%#",sortedKeysArray);
NSMutableDictionary *sortedValues = [[NSMutableDictionary alloc] init];
for (NSString *key in sortedKeysArray) {
[sortedValues setValue:[vehiclesDictionary valueForKey:[NSString stringWithFormat:#"%#",key]] forKey:key];
}
NSLog(#"%#",sortedValues);
Pls help me
You cannot sort an NSDictionary, it is an unsorted collection type. You will need to store your keys in an array and sort this and use it to access the NSDictionary in order.
Based on your code above, it could be modified as follows, e.g.
NSDictionary *dict = [NSDictionary dictionary];
NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
for (NSString *key in sortedKeys) {
NSLog(#"%#", [d objectForKey:key]);
// Do something with the object here
}
Here you can pass around the sortedKeys array with the NSDictionary, and use the sortedKeys array for in-order access to your NSDictionary.
A more concise approach to get the array, but with the same outcome as above, would be using:
NSDictionary -keysSortedByValueUsingComparator as shown here.
As others have mentioned, NSDictionaries cannot be sorted. However, you could do something like this:
-(NSArray *)sortedKeysFromDictionary:(NSDictionary *)dictionary ascending:(BOOL)ascending
{
/* get all keys from dictionary */
NSArray *allKeys = [dictionary allKeys];
NSString *key = #"id"; // using "id" as key here
/* sort keys */
NSSortDescriptor *dateDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:ascending];
return [NSArray arrayWithArray:[allKeys sortedArrayUsingDescriptors:#[dateDescriptor]]];
}
This will take all the keys from your dictionary, sort them in ascending or descending order as you desire and return that as an NSArray. This array can then be used to access the original dictionary. A sample implementation would look something like this:
for (NSString *key in [self sortedKeysFromDictionary:sampleDic ascending:NO])
{
/* get value from current key */
NSDictionary *currentDic = [sampleDic objectForKey:key];
}
in my project i applied the following code
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSLog(#" for ref id =%# ,name of diagnose=%# data is= %#",refidstr,diagnosedictforname ,diagnosisdict);
and the output in console is comes out as in the form
str : {
diagnoses = (
{
Diagnoses = {
"diagnosis_name" = "TRANSIENT ISCHEMIA";
};
DiagnosesHospitals = {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
};
}
);
response = 200;
}
ref id =3341 ,name of diagnose={
"diagnosis_name" = "TRANSIENT ISCHEMIA";
} data is= {
"charge_amt" = "1300.00";
discharges = "11200.00";
"hospital_id" = 3341;
id = 163080;
"medicare_amt" = "100.00";
"total_amt" = "1100.00";
}
now i just want to embed the values of both the Dictionaries into one dictionary
someone please help me to sort out this issue.
Make a mutable copy of the first dictionary:
NSMutableDictionary * mutDic = [dic1 mutableCopy];
and then:
[mutDic addEntriesFromDictionary:dic2];
Try this code:
NSDictionary *dict6 = [self cleanJsonToObject:responseData];
NSLog(#"str : %#",dict6);
NSMutableDictionary *diagnosisdict = [[[dict6 objectForKey:#"diagnoses"] objectAtIndex:0] objectForKey:#"DiagnosesHospitals"];
NSDictionary *diagnosedictforname = [[[dict6 objectForKey:#"diagnoses"]objectAtIndex:0]objectForKey:#"Diagnoses"];
NSArray *keys = [diagnosedictforname allKeys];
for (int i =0; i < keys.count; i++) {
NSString *key = [keys objectAtIndex:i];
[diagnosisdict setValue:[diagnosedictforname valueForKey:key] forKey:key];
}
NSLog(#"your dic -> %#", diagnosisdict);
I have NSMutableArray data as below.
(
{
Id = "-1";
NameEn = Country;
},
{
Id = 14;
NameEn = Iran;
},
{
Id = 11;
NameEn = Jordan;
},
{
Id = 5;
NameEn = "United Arab Emirates";
},
{
Id = 4;
NameEn = "Suadi Arabia";
},
{
Id = 3;
NameEn = Kuwait;
},
{
Id = 10;
NameEn = Yemen;
},
{
Id = 6;
NameEn = Oman;
},
{
Id = 12;
NameEn = Syria;
},
{
Id = 7;
NameEn = Qatar;
},
{
Id = 13;
NameEn = Lebanon;
},
{
Id = 1;
NameEn = Egypt;
},
{
Id = 8;
NameEn = "Bahrain Kingdom";
}
)
I want to find the location where Id=5.
Any idea how can I do?
I tried with below.
NSString *myCountry = [[NSUserDefaults standardUserDefaults] valueForKey:#"mCountryId"];
NSUInteger indexOfTheObject = [feedsCountry indexOfObject: myCountry];
NSLog(#"indexOfTheObject===%i==%#", indexOfTheObject, myCountry);
if (NSNotFound == indexOfTheObject) {
NSLog(#"not found...");
}
But I get output as not found... for mCountryId as 5.
Use an NSDictionary instead, and key your entries by Id; e.g.:
NSMutableDictionary* dictionary = [NSMutableDictionary new];
[dictionary setObject:#"Egypt" forKey:#"1"];
// (etc...)
EDIT: If you already have an array and can not change that, use a for loop like this:
for(NSDictionary* entry in givenArray){
NSString* key = [entry objectForKey:#"Id"];
NSString* value = [entry objectForKey:#"NameEn"];
[dictionary setObject:value forKey:key];
}
NSPredicate * filter = [NSPredicate predicateWithFormat:#"Id = 5"];
NSArray * filtered = [array filteredArrayUsingPredicate:filter];
The first object in filtered is the dictionary with Id = 5