Merge all values of array in a dictionary

Viewed 101

I have a dictionary of var tags = [String:[String]](). When returning the values to the REST endpoint I need to merge all the values in [String] array. Can I do something with using

self.tags.map { $0.value }

But no clue how to get a single array using all the values arrays from dictionary.

2 Answers

Yes you can do that using flatMap

var tags = [String:[String]]()
tags["1"] = ["2","3"]
tags["2"] = ["4","5"]

let arr = tags.values.flatMap{$0}

OR

let arr = tags.flatMap(\.value)

Prints

print(arr) // ["2","3","4","5"]

You can use flatMap to achieve this:

var tags   = [String:[String]]()
var values = tags.flatMap { $0.value }
// or using keypath
var values = tags.flatMap(\.value)

Or use flatMap on values like this:

var values = tags.values.flatMap{$0}
Related