swift - Using `flatMap().filter().map()` together on a multidimensional array -
i use following method find identifier
isbooltrue==true
nested array (screenshot of array , data structure below)
func extractidentifiers(mainarray: [mainitem]) -> [int]? { var selected = [int]() mainarray.foreach { element in let integers = element.innerarray?.filter({ $0.isbooltrue }).map { int($0.identifier)! } if !(integers?.isempty ?? true) { selected += integers! } } return selected.isempty ? nil : selected }
question: possible use sort of chaining flatmap().filter().map()
produce same result [int]?
, able eliminate use of mainarray.foreach
, conditional checks selected.isempty
, integers?.isempty
?
note: need within above method extractidentifiers
, below find data , structure play around, screenshot of array.
thanks in advance!
structure & data:
struct inneritem { let identifier: string var isbooltrue: bool } struct mainitem { var innerarray: [inneritem]? } let str = "[{\"innerarray\":[{\"identifier\":\"0\",\"isbooltrue\":true},{\"identifier\":\"1\",\"isbooltrue\":false}]},{\"innerarray\":[{\"identifier\":\"3\",\"isbooltrue\":true},{\"identifier\":\"4\",\"isbooltrue\":false}]},{\"innerarray\":null}]" let data = str.data(using: string.encoding.utf8)! let json = try jsonserialization.jsonobject(with: data, options: .allowfragments) as? [[string : any]] var mainarray = [mainitem]() json!.foreach { dict in if let array = dict["innerarray"] as? [[string: any]] { let innerarray = array.map { inneritem(identifier: $0["identifier"] as! string, isbooltrue: $0["isbooltrue"] as! bool) } mainarray.append(mainitem(innerarray: innerarray)) } }
tests & output
var selected: [int]? // fill array `identifier` // test1 selected = extractidentifiers(mainarray: mainarray) // output: [0, 3] // test2 mainarray[0].innerarray![0].isbooltrue = false selected = extractidentifiers(mainarray: mainarray) // output: [3] // test3 mainarray[1].innerarray![0].isbooltrue = false selected = extractidentifiers(mainarray: mainarray) // output: nil
my approach flatten nested array array of dictionaries using double flatmap
, filter object true
value , @ last use map "identifier" value.
let result = data.flatmap { $0.flatmap { $0.value } } // line flatten 1 level .filter { $0["isbooltrue"] == true } .map { $0["identifier"] } print(result) // output ["0", "3"]
note: have better understanding on output, try print line line
Comments
Post a Comment