Home > Mobile >  Swift - Combining an array of objects by an attribute
Swift - Combining an array of objects by an attribute

Time:12-16

What I have is:

var filters = [Filter]

class Filter {
   var type: String?
   var value: String?
}

What I would like to do is reduce/map/filter that array into a new array of Filter that combines Filters by type, but keeps an array of their values.

For example:

Begin:

var filters = [Filter(type: "size", value: "10"), Filter(type: "size", value: "20"), Filter(type: "color", value: "green")]

And then end with:

var filtersByType = [Filter(type: "size", value: "10|20"), Filter(type: "color", value: "green")]

CodePudding user response:

You can create a dictionary using Dictionary(:uniquingKeysWith:) and then extract the values

let filtersByType = Dictionary(filters.map { ($0.type, $0)}, uniquingKeysWith: {
    $0.value = "\($0.value ?? "")|\($1.value ?? "")"
    return $0
}).values

I have a very basic handling of nil values in this code snippet that you probably want to improve (or perhaps consider to not use optional properties at all).

  • Related