1

I am trying to filter out arrays in an array condition

public struct SalesDO: Entity {
   public var ID: String = UUID().uuidString
   public var isDeleted: Bool = false
   public var salesItems = [SalesItemDO]()
}

public struct SalesItemDO: Entity {
   public var ID: String = UUID().uuidString
   public var isDeleted: Bool = false
   public var modifiers = [SalesItemModifierDO]()
}

public struct SalesItemModifierDO: Entity {
   public var ID: String = UUID().uuidString
   public var isDeleted: Bool = false
}

What i am trying to achieve is to filter out those SalesItem which is not deleted, together with the sales item modifiers inside not deleted as well

I try to use the Swift filter array function, but it is compiler error

let rawSales = self.service.getSales(object: SalesDO()) as? SalesDO
if var sales = rawSales {
   let filteredSalesItem = sales.salesItems.filter({$0.modifiers.filter({$0.isDeleted == false})})
}.filter({$0.isDeleted == false})

I also tried this code

// It becomes SalesItemModifierDO array
let filteredsales = sales.salesItems.flatMap({$0.modifiers.filter({$0.wbDeleted == false})}).filter({$0.wbDeleted == false})

For example

Item A is not deleted
   => Modifier 1
   => Modifier 2
   => Modifier 3 : Deleted
Item B is deleted 
   => Modifier 1
   => Modifier 2

I am trying to achieve a function that will only display Item A with only 2 modifiers, because the modifier 3 is already deleted.

Can someone guide on what I am missing? Any help given is highly appreciated. Thanks

1 Answer 1

1

You can filter the array to remove sale items that are deleted, then map the remaining ones to remove modifiers where the modifier is deleted.

let filteredSalesItem = sales.salesItems.filter({ !$0.isDeleted }).map { (item) -> SalesItemDO in
    var newItem = item // Need to make mutable interim item to change modifiers array
    newItem.modifiers = newItem.modifiers.filter({ !$0.isDeleted })
    return newItem
}
Sign up to request clarification or add additional context in comments.

9 Comments

Hi Sir, thanks for the reply. The code above is working for filtering sales items, but the item modifier inside the sales item is not being filtered.
Just checking - you want to filter out any sales item that is itself deleted, or has a true isDeleted modifier?
Basically I need to check SalesItems those are not deleted. After filtered the SalesItems those are not deleted, check the modifier inside and only display those are not deleted as well.
I have made a small change - please try it. It should both out at once.
Sir, i have updated the question for better clarity. Thanks
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.