Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Filter Nested Array

I have a NSMutableArray which it self has many arrays inside it. Inside each array at all index they further had custom objects of class given bellow.

Class User:NSObject{
    var name = ""
    var userName = ""
    var email = ""
    var age = 0
    var gender = ""
    var 
}

I want to filter this nested array with respect to two objects. For example if user type some text in searchBar and check that text in that nested array if that text matches with the name or the userName or both.

like image 777
Ahsan Imtiaz Avatar asked Dec 03 '22 23:12

Ahsan Imtiaz


1 Answers

let nestedArray: [[User]] = [[user1, user2], [user3], [user4, user5]]

let searchName = "foo"
let filteredArray = nestedArray.map({
        return $0.filter({ $0.name == searchName })
    }).filter({ $0.count > 0 })

This is a purely functional way that results in a new nested array that only contains arrays with matching users and these arrays also will only contain the matching users.

like image 187
matteok Avatar answered Dec 23 '22 06:12

matteok