5

Very new to Swift I have a multidimensional array of some 500 records

[10, 2, 4, 10, 23, 56]
[0, 12, 14, 20, 28, 42]
[0, 2, 4, 10, 26, 54]
[1, 24, 34, 40, 47, 51]
[1, 23, 24, 30, 33, 50]

so that I would have

[0, 2, 4, 10, 26, 54]
[0, 12, 14, 20, 28, 42]
[1, 23, 24, 30, 33, 50]
[1, 24, 34, 40, 47, 51]
[10, 2, 4, 10, 23, 56]

I am fine for the individual record sort.
But when looking at the 500 records, to sort the records for the first column I used arr.sort { $0[0] < $1[0] }. which worked fine, I need to extend that to columns 2,3,4,5,6. I want to be able to sort on Column 1 then by 2, by 3, by 4, by 5, by 6.

2
  • Are you trying to sort each column, or are you trying to order the rows but keep the rows intact? Could you edit your question and give the expected output for your sample array? Commented Apr 26, 2018 at 1:20
  • Hope change to question helps a little Commented Apr 26, 2018 at 1:28

1 Answer 1

4

Assuming that all subarrays contains 6 elements you can use a tuple (which conforms to Comparable to an arity of 6) to sort your array:

let array = [[10, 2, 4, 10, 23, 56],
             [0, 12, 14, 20, 28, 42],
             [0, 2, 4, 10, 26, 54],
             [1, 24, 34, 40, 47, 51],
             [1, 23, 24, 30, 33, 50]]

let sorted = array.sorted(by: {
     ($0[0],$0[1],$0[2],$0[3],$0[4],$0[5]) < ($1[0],$1[1],$1[2],$1[3],$1[4],$1[5])
})
print(sorted) // [[0, 2, 4, 10, 26, 54],
              //  [0, 12, 14, 20, 28, 42],    
              //  [1, 23, 24, 30, 33, 50], 
              //  [1, 24, 34, 40, 47, 51],
              //  [10, 2, 4, 10, 23, 56]]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Leo, so simple works a treat. I had tried variations of the sorted function previously and could only get errors.

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.