Alen Alexander
Alen Alexander

Reputation: 735

Filter array of custom objects with an attribute and Map in Swift

My model class is as below :

struct Job: Decodable, Equatable, Hashable {
   var id: Int?
   var status: String?
   var priority: String?
}

I have 2 array of objects(job) as :

 var jobModel = [Job]()
 var filteredJobModel = [Job]()

Case : jobModel has 5 elements. filteredJobModel has 2 elements( subset of jobModel ). In filteredJobModel, the value for status for both objects has been changed by search operation. I would like to update the jobModel back with filteredJobModel, where the object matches the id attribute.

Is there any way by which I can achieve this case? I would have been able to use filter & map for [String], but, I would like to know how to implement higher order functions for array of custom objects.

Upvotes: 0

Views: 2081

Answers (1)

Duncan C
Duncan C

Reputation: 131398

for (index, job) in idsJobModel.enumerated() {
    if let match = arrFiltetered.first( where: {job.id == $0.id} ) {
     idsJobModel[index] = match
   }
}

Or if you prefer using map:

idsJobModel = idsJobModel.map {
    let myID = $0.id
    if let match = arrFiltetered.first( where: {myID == $0.id} ) {
        return match
    } else {
        return $0
    }
}

Either version of the code above will have O(n²) performance, so it will get dramatically slower as your arrays get larger than ≈30 elements. It would need to be tweaked to perform well on larger arrays.

Upvotes: 1

Related Questions