0

Can I expand the dictionary to an array of pairs in Swift 5 using map/reduce or will I have to do a for each ?

let dict = ["A": ["1","2","3","4"],
            "B": ["5","6","7","8"]]

???

//result = [["A", "1"],["A", "2"],....["B", "5"],....]
Duncan Groenewald
  • 8,496
  • 6
  • 41
  • 76
  • 3
    Possible duplicate of [How to convert dictionary to array](https://stackoverflow.com/questions/31845421/how-to-convert-dictionary-to-array) – MQLN Jul 25 '19 at 03:34
  • @MQLN doesnt really seems like a duplicate its not the same problem – Olympiloutre Jul 25 '19 at 03:43

3 Answers3

2
let result = dict.map { (letter: String, digits: [String]) in
    return digits.map { digit in
        return [letter, digit]
    }
}.reduce([]) {
    $0 + $1
}
Hong Wei
  • 1,397
  • 1
  • 11
  • 16
  • 2
    `reduce([]) { $0 + $1 }` can just be replaced with `reduce([], +)`. At the minimum, you should use `reduce(into: []) { $0 += $1) }`, or else you get quadratic time complexity, or even better, just use `.flatMap { $0 }` – Alexander Jul 25 '19 at 03:48
0

This one is shortest solution.

let result = dict.map { dic in
        dic.value.map { [dic.key : $0] }
    }.reduce([], +) 
Jaydeep Vora
  • 6,085
  • 1
  • 22
  • 40
  • You should use reduce(into: []) { $0 += $1) }, or else you get quadratic time complexity, or even better, just use .flatMap { $0 } – Alexander Jul 25 '19 at 04:13
0

Here's a solution that doesn't need reduce:

let dict = ["A": ["1","2","3","4"],
            "B": ["5","6","7","8"]]
let result = dict.map { kv in kv.value.map { [kv.key, $0] } }.flatMap { $0 }
rmaddy
  • 314,917
  • 42
  • 532
  • 579