Reputation: 1046
Given an input like so:
let m = ["one": ["1","2","3"],
"two":["4","5"]
]
how can I use map/reduce to produce the output like:
["1","2","3","4","5"]
I'm not very swifty, and trying to learn it but I cant seem to figure out an efficient way to do this simple operation. My verbose approach would be like so:
var d = [String]()
for (key, value) in m {
value.forEach { (s) in
d.append(s)
}
}
print(d)
I'm sure this can be a 1 liner, could someone assist?
Upvotes: 0
Views: 860
Reputation: 63271
All you need is a single flatMap
:
let result = dict.flatMap { _, values in values }
Upvotes: 2