4

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)]
2
  • seems like a job interview's question or a homework... Commented Dec 19, 2017 at 15:13
  • @holex I can do this with for loop,but this could be more elegant. Commented Dec 19, 2017 at 15:21

1 Answer 1

9
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 indexenumerated() 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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.