-4

Ex.

Input: var array: [Int] = [1, 2, 3, 1, 3, 4, 2, 1]

Output:

[[1, 1, 1], [2, 2], [3, 3], [4]]

1

1 Answer 1

4

A solution with Dictionary(grouping:by:)

let array = [1, 2, 3, 1, 3, 4, 2, 1]
let output = Dictionary(grouping: array, by: {$0})
    .values
    .sorted(by: { $0[0] < $1[0] })
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you. It's really help me lots.
Hello @vadian it's return Dictionary not array.
No, it returns array.
Yes, I am not use sorted that's why. Thank you.
I wonder how this compares to Dictionary(grouping: array, by: { $0 }) .sorted(by: { $0.key < $1.key }) .map { $0.value }, performance-wise
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.