serdar aylanc
serdar aylanc

Reputation: 1347

Swift - How to filter multi dimentional Array

I have arrays inside arrays like this;

var trucks: [boxes]
var boxes: [items]
var items: [fruits]

I want to find "apple" inside the items and keep them inside the trucks array. (I will reload the collectionView and display new filtered sections ...etc)

I tried:

let myArray = trucks.boxes

let searchArray = myArray.flatMap {
  $0.items
     .filter {$0.name == "apple"}
}

But what I get is the items array.

Upvotes: 1

Views: 60

Answers (1)

Joakim Danielson
Joakim Danielson

Reputation: 51955

I am not exactly sure what your structure of class/struct is but given the following definition the result will contain the boxes that has items with name "apple"

struct Truck {
    let boxes: [Box]
}

struct Box {
    let items: [Item]
}

struct Item {
    let name: String
}

let truck = Truck(boxes: [
    Box(items: [Item(name: "Banana")]),
    Box(items: [Item(name: "Apple"), Item(name: "Pear")])
])

let searchArray = truck.boxes
    .filter { box in
        box.items.contains(where: { item in item.name.lowercased() == "apple" })
    }

Upvotes: 1

Related Questions