Search and filter in a Swift array of dictionaries for specific value

In this post, we will learn how to search in an array of dictionaries in Swift. Below is the problem statement :

  • One array of dictionaries is given.
  • Search through the array items and create one new array of dictionaries by filtering out values based on specific properties.

I will show you two different ways to solve it. The first method uses map() and the second one uses filter. Both methods creates one new array without changing the original.

Method 1: With map() :

We can use map to iterate through the array elements one by one and build one new array by joining all elements those passed the check.

var url_data_1: [String:String?] = ["id": "1", "url": "https://www.google.com"]
var url_data_2: [String:String?]  = ["id": "2", "url": "https://www.google.com"]
var url_data_3: [String:String?]  = ["id": nil, "url": "https://www.google.com"]
var url_data_6: [String:String?]  = ["id": nil, "url": "https://www.google.com"]

var url_arr = [url_data_1, url_data_2, url_data_3, url_data_6]

var newArr = [[String: String?]]();

url_arr.map{item in
    if let itemId = item["id"]{
    if(itemId != nil){
        newArr.append(item)
    }
    }
    return;
}

print(newArr)

In this example, we are creating one new array by removing all elements with id=nil.

Swift filter array of dictionaries

urlarr_ is the original array with data and newArr is the new array. We are also unwrapping the

It will print :

[["id": Optional("1"), "url": Optional("https://www.google.com")], ["url": Optional("https://www.google.com"), "id": Optional("2")]]

Method 2: Using filter :

filter is easier than map(). This method filters out the elements based on a validation. Let’s check the below program :

var url_data_1: [String:String?] = ["id": "1", "url": "https://www.google.com"]
var url_data_2: [String:String?]  = ["id": "2", "url": "https://www.google.com"]
var url_data_3: [String:String?]  = ["id": nil, "url": "https://www.google.com"]
var url_data_6: [String:String?]  = ["id": nil, "url": "https://www.google.com"]

var url_arr = [url_data_1, url_data_2, url_data_3, url_data_6]

var newArr = [[String: String?]]();

newArr = url_arr.filter{item in
    if let itemId = item["id"] {
        return itemId != nil
    }
    return false
}

print(newArr)

It is almost similar to map(). The only difference is that we are returning one boolean value based on the id is nil or not.

It will print the same output.

Swift filter array of dictionaries using filter

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊