Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array of dictionaries by NSString

while implementing search functionality I need to filter array of dictionaries. I am using auto complete textfield method for search bar and am storing it into string. I can able to parse the array,But facing with below json

[{"CertProfID":"4","Name":"Dodge","Location":"loc4","City":"city4","State":"state4","Zip":"zip5","Website":"http:\/\/cnn.com","Phone":"phone4","Email":"email4"},
{"CertProfID":"5","Name":"cat","Location":"loc5","City":"city5","State":"State5","Zip":"zip5","Website":"web5","Phone":"phone5","Email":"email5"}]

Here I need to filter the dictionaries to make it finish

I tried with below code but its returning array with null values :(

 NSString *substring = [NSString stringWithString:textField.text];
  NSLog(@"substring %@",substring);
  NSMutableArray *arr2Filt= [arraylist valueForKey:@"Name"];
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF  contains[c] %@",substring];
  filteredarr = [NSMutableArray arrayWithArray:[arr2Filt filteredArrayUsingPredicate:predicate]];
like image 822
Code cracker Avatar asked Dec 05 '22 04:12

Code cracker


1 Answers

This code will solve your problem it will return an array of dictionaries

NSString *substring = [NSString stringWithString:textField.text];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"Name contains[c] %@",searchString];
NSArray *filteredArry=[[arrayOfDict filteredArrayUsingPredicate:predicate] copy];

arrayOfDict is your original array of dictionaries

Swift 4.2 Version:::

let namePredicate = NSPredicate(format: "Name contains[c] %@",searchString)

let filteredArray = arrayOfDict.filter { namePredicate.evaluate(with: $0) }

print("names = \(filteredArray)")

Hope it will help you

like image 110
Muhammad Waqas Bhati Avatar answered Dec 22 '22 22:12

Muhammad Waqas Bhati