1

I shall like to sort out an array in order chronological. I know not at all how to take myself there ... Here is the array:

 [["FM", "TEL", "ID", "2017-06-17 18:16:29 +0000", "TYPE", "inbox"], ["FM", "TEL", "ID", "2017-06-17 18:17:24 +0000", "TYPE", "no", "send"], ["Jm", "TEL", "ID", "2017-06-17 19:25:27 +0000", "TYPE", "no", "send"]]

I tried with that but that did not work ....

 str.sort({$0[3].date > $1[3].date})

I shall like the most recent date at the beginning, the output should be like this:

 [["Jm", "TEL", "ID", "2017-06-17 19:25:27 +0000", "TYPE", "no", "send"], ["FM", "TEL", "ID", "2017-06-17 18:17:24 +0000", "TYPE", "no", "send"], ["FM", "TEL", "ID", "2017-06-17 18:16:29 +0000", "TYPE", "inbox"], ["FM", "TEL", "ID", "2017-06-17 18:17:24 +0000", "TYPE", "no", "send"]]
6
  • what should be your output? Commented Jun 18, 2017 at 7:27
  • This has the thing you need in every language - rosettacode.org/wiki/Sort_using_a_custom_comparator Commented Jun 18, 2017 at 7:28
  • Did you try str.sort {$0[3].date > $1[3].date} stackoverflow.com/questions/26719744/… Commented Jun 18, 2017 at 7:29
  • Not working with {$0[3].date > $1[3].date} ... Commented Jun 18, 2017 at 7:33
  • 1
    $0[3].date What's that call .date ? $0[3] is a String. You need to convert it into (NS)Date with (NS)DateFormatter. Also, I strongly suggest to use a proper class/struct rather than a array to keep your data. Commented Jun 18, 2017 at 10:28

1 Answer 1

1

Use dateformatter to convert strings into date first and then compare them:

let str = [["FM", "TEL", "ID", "2017-06-17 18:16:29 +0000", "TYPE", "inbox"], ["FM", "TEL", "ID", "2017-06-17 18:17:24 +0000", "TYPE", "no", "send"], ["Jm", "TEL", "ID", "2017-06-17 19:25:27 +0000", "TYPE", "no", "send"]]

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"

let sorted = str.sorted(by: {dateFormatter.date(from: $0[3])!  > dateFormatter.date(from: $1[3])!})
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.