Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Sort an array in an ascending order swift 2.3

[{
msg = "Hi This is Jecky";
name = Susheel;
sender = 77;
timestamp = 1464241769520;
username = susheel;
}, {
msg = Dubai;
name = Jecky;
sender = 78;
timestamp = 1464246547147;
username = Jecky;
}, {
msg = "How are you ?";
name = Susheel;
sender = 77;
timestamp = 1464243480381;
username = susheel;
}, {
msg = "Aje dekhai nai";
name = Jecky;
sender = 78;
timestamp = 1464244974198;
username = Jecky;
}]
  • I have an array like this. I want to sort this array using timestamp in swift 2.3 or latest version of swift. Can anyone help me for this ?
like image 299
Jecky Avatar asked May 27 '16 05:05

Jecky


2 Answers

let array=[
        [
            "msg":"Hi This is Jecky",
            "name":"Susheel",
            "sender":77,
            "timestamp":1464241769520,
            "username":"susheel",
        ],
        [
            "msg":"Dubai",
            "name":"Jecky",
            "sender":78,
            "timestamp":1464246547147,
            "username":"Jecky",
        ],
        [
            "msg":"How are you ?",
            "name":"Susheel",
            "sender":77,
            "timestamp":1464243480381,
            "username":"susheel",
        ],
        [
            "msg":"Aje dekhai nai",
            "name":"Jecky",
            "sender":78,
            "timestamp":1464244974198,
            "username":"Jecky",
        ],
    ]
    print("array = \(array)")
    let sortedArray=array.sort { (obj1, obj2) -> Bool in
        return (obj1["timestamp"] as! Double) < (obj2["timestamp"] as! Double)
    }
    print("sortedArray = \(sortedArray)")
like image 163
fnc12 Avatar answered Oct 05 '22 23:10

fnc12


If your array is mutable you can user sortInPlace

yourArray.sortInPlace{$0.timestamp < $1.timestamp}

and if not, you can create a new array from sort, like suggested by Kristijan (although no need for parentheses on trailing closures):

let newArray = yourArray.sort{$0.timestamp < $1.timestamp}
like image 20
T. Benjamin Larsen Avatar answered Oct 06 '22 00:10

T. Benjamin Larsen