Home How to filter a NSArray by Key:value, that is in a NSDictionary
Reply: 2

How to filter a NSArray by Key:value, that is in a NSDictionary

Hunter Published in 2018-02-14 08:33:18Z

Im trying to figure out how to filter out the Dictionary of NSArrays by the value "name"

// Is an Array of a dictionary, by key : values

var teamFilteredList = [[String:Any]]()
var teamList = [[String:Any]]() 


    let string = "https://api/connect/"
    let url = NSURL(string: string)
    let request = NSMutableURLRequest(url: url! as URL)
    request.httpMethod = "GET"
    let session = URLSession.shared
    let tache = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! NSArray {
            teamList = jsonObj as! [[String : Any]]

            DispatchQueue.main.async {

This code is the result and gets put in teamList


    id = 1;
    logo = "testLogo";
    name = "testTeam1";
    "url" = "https://example.com";
    id = 2;
    logo = "testLogo";
    name = "testTeam2";
    "url" = "https://example.com";
    id = 3;
    logo = "testLogo";
    name = "testTeam3";
    "url" = "https://example.com";

Example of what it looks like once put in teamList:

let example = [[id: "1", logo: "image", name: "testTeam1", url: "https"], [id: "2", logo: "image", name: "testTeam2", url: "https"]] 

Code Trying to Filter:

 let array2Name = teamFilteredList.flatMap { $0["name"] }
    teamFilteredList = teamList.reduce(teamFilteredList, { result, value in
        !array2Name.contains(where: { $0 as! _OptionalNilComparisonType == value["testTeam3"] }) ? result + [value]: result

So far this code has been horrible. But there's nothing else online that tells me how to do it cut dry. So I've been stuck.

leads to crash:

Could not cast value of type '__NSCFString'


I have a collection view that is populated from a fetch by a NSURL that gives me a Dictionary filled with NSArrays and i want to filter out all the NSArray indexes in that dictionary by a value that is already in the NSArray Indexes by the key: "name"

This answered Question in this link final answer, but its not up to date and yields errors. here

vadian Reply to 2018-02-14 09:40:16Z

It's so, so much easier with a custom struct and JSONDecoder

Create a struct

struct Team : Decodable {
    let id : Int
    let logo : String
    let name : String
    let url : URL

Create the arrays

var teamList = [Team]()
var teamFilteredList = [Team]()

Decode the JSON

let string = "https://api/connect/"
let url = URL(string: string)!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
    if let error = error { print(error); return }
    do {
        self.teamList = try JSONDecoder().decode([Team].self, from: data!)
        DispatchQueue.main.async {
    } catch {

And filter the array

teamFilteredList = teamList.filter{ $0.name == "testTeam3" }
user9335240 Reply to 2018-02-14 09:56:44Z

Try to use this predicate

teamFilteredList.filter({ fromDict in return !array2Name.contains(where: { $0 == fromDict["name"] as? String ?? ""})})

The trick is that Swift isn't expressive in its errors. It says that don't use where, why? because the compiler really expects a String, because your closure is not correct.

And if the array2Name is a dictionary also. Try to change the where clause to:

where: { ($0["name"] as? String ?? "<<Empty1>>") == (fromDict["name"] as? String ?? "<<Empty2>>") }

So the whole function would be:

teamFilteredList.filter({ fromDict in return !array2Name.contains(where: { ($0["name"] as? String ?? "<<Empty1>>") == (fromDict["name"] as? String ?? "<<Empty2>>") })})

If you want to learn more effective functional programming and you don't mind some JavaScript, try this

Learn Effective Functional Programming in JavaScript)

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.421567 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO