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
  • 7,772
  • 5
  • 35
  • 68
  • 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,367
  • 1
  • 11
  • 15
  • 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
  • 5,883
  • 1
  • 21
  • 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
  • 307,833
  • 40
  • 508
  • 550