简体   繁体   中英

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 ?
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)")

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}
customArray.sortInPlace { 
  (element1, element2) -> Bool in
   return element1.someSortableField < element2.someSortableField
}

Check this out https://www.hackingwithswift.com/example-code/arrays/how-to-sort-an-array-using-sort

按属性“timestamp”排序

array.sorted{$1["timestamp"] as? Long > $0["timestamp"] as? Long}

You can get this functionality using extension:

extension NSArray{
 //sorting- ascending
  func ascendingArrayWithKeyValue(key:String) -> NSArray{
    let ns = NSSortDescriptor.init(key: key, ascending: true)
    let aa = NSArray(object: ns)
    let arrResult = self.sortedArray(using: aa as! [NSSortDescriptor])
    return arrResult as NSArray
  }

  //sorting - descending
  func discendingArrayWithKeyValue(key:String) -> NSArray{
    let ns = NSSortDescriptor.init(key: key, ascending: false)
    let aa = NSArray(object: ns)
    let arrResult = self.sortedArray(using: aa as! [NSSortDescriptor])
    return arrResult as NSArray
  }
}

use like this:

 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",
        ],
      ]

    let a = NSArray.init(array: array)
    let filArray = a.ascendingArrayWithKeyValue(key: "timestamp")
    print(filArray)

=> First, convert your Json to Objects. (check this link to do that :- http://roadfiresoftware.com/2015/10/how-to-parse-json-with-swift-2/ )

=> Then declare your Array as a typed array so that you can call methods when you iterate:

var array : [yourObjectClassName] = []

=> Then you can simply sort the value by :

array.sort({ $0.name > $1.name })

The above example sorts all the arrays by name. If you need to sort by timeStamp you can change the name to timeStamp ..etc

Check this link for more sorting examples : Swift how to sort array of custom objects by property value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM