Given an array that contains elements like this:
let array = [[a], [b, c], [d, e, f]]
Is there an elegant way to convert this array to an array which returns a tuple with the index of the outer array:
let result = [(a, 0), (b, 1), (c, 1), (d, 2), (e, 2), (f, 2)]
let array = [["a"], ["b", "c"], ["d", "e", "f"]]
let result = zip(array, array.indices).flatMap { subarray, index in
subarray.map { ($0, index) }
}
result
is:
[("a", 0), ("b", 1), ("c", 1), ("d", 2), ("e", 2), ("f", 2)]
I used zip(array, array.indices)
instead of array.enumerated()
because you specifically asked for a tuple with the array index — enumerated()
produces tuples with zero-based integer offsets. If your source collection is an array, it doesn't make a difference, but other collections (like ArraySlice
) would behave differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With