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.

vacawama
  • 150,663
  • 30
  • 266
  • 294
graham4d
  • 53
  • 5
  • 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? – vacawama Apr 26 '18 at 01:20
  • Hope change to question helps a little – graham4d Apr 26 '18 at 01:28

1 Answers1

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]]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Thanks Leo, so simple works a treat. I had tried variations of the sorted function previously and could only get errors. – graham4d Apr 26 '18 at 02:03