I have an array that contains another array. I need to filter parent array with a value in the child array. I am actually confused on how to go about it and if it is possible
struct ConnectionDetailSection {
var connections: [ConnectionDetail]
let type: ConnectionType
let itemsType: [ConnectionDetailSectionContentType]
let itemsIndex: [IndexPath] // permission's table view indexpath
}
struct ConnectionDetail {
var dsAccountId: String?
}
I want to filter [ConnectionDetailSection] based on dsAccountId. is this possible?
CodePudding user response:
Your question is not properly clear to me, so please update your question with input and required output which may lead to change in my answer.
The answer is yes, it is possible to filter data in a nested array.
Just for simplicity, I have removed all the extra keys in the structure.
struct ConnectionDetailSection {
var connections: [ConnectionDetail]
}
struct ConnectionDetail {
var dsAccountId: String
}
let detail: [ConnectionDetailSection] = [
.init(connections: [.init(dsAccountId: "stack"), .init(dsAccountId: "queue"), .init(dsAccountId: "array"), .init(dsAccountId: "tree")]),
.init(connections: [.init(dsAccountId: "sorting"), .init(dsAccountId: "searching"), .init(dsAccountId: "bfs"), .init(dsAccountId: "dfs")]),
]
let filteredData = detail.filter({ data in
return data.connections.contains(where: { $0.dsAccountId == "bfs" })
})
print(filteredData) //[[.init(dsAccountId: "sorting"), .init(dsAccountId: "searching"), .init(dsAccountId: "bfs"), .init(dsAccountId: "dfs")]]
Now, let's say if we have an array => ConnectionDetailSection. In this array, there are nested arrays, in this example we have data structures and algorithms. So, if we want to filter out the array => ConnectionDetailSection, on the basis of algorithm like bfs, then we will just filter out the array on the basis of it's nested array and check if contains that matching dsAccountId or not, in our case the required dsAccountId is bfs.
So, it will return the filtered array and this is how you can filter the nested array.
