I have an array containing an object called HistoryObject
and it has properties such as "date", "name", etc.
I am sorting the array like so:
let sortedArray = HistoryArray.sort({ $0.date.compare($1.date) == NSComparisonResult.OrderedDescending})
which is supposed to sort the date from newer to oldest. For example:
etc..
But when my array contains "Jul 2, 2016" the sorted array becomes:
Where "Jul 2, 2016" should be on top after sorting, now it's on the bottom? How can I fix this problem?
To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.
const arr = [{id: 1, date: 'Mar 12 2012 10:00:00 AM'}, {id: 2, date: 'Mar 8 2012 08:00:00 AM'}]; We are required to write a JavaScript function that takes in one such array and sorts the array according to the date property of each object. (Either newest first or oldest first).
To sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
Using Swift 4 & Swift 3
let testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"] var convertedArray: [Date] = [] var dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd" for dat in testArray { let date = dateFormatter.date(from: dat) if let date = date { convertedArray.append(date) } } var ready = convertedArray.sorted(by: { $0.compare($1) == .orderedDescending }) print(ready)
Using Swift 2
For example you have the array with dates and another 1 array, where you will save the converted dates:
var testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"] var convertedArray: [NSDate] = []
After that we convert the dates:
var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd MM, yyyy"// yyyy-MM-dd" for dat in testArray { var date = dateFormatter.dateFromString(dat) convertedArray.append(date!) }
And the result:
var ready = convertedArray.sort({ $0.compare($1) == .OrderedDescending }) print(ready)
For Swift 3
var testArray = ["25 Jun, 2016", "30 Jun, 2016", "28 Jun, 2016", "2 Jul, 2016"] var convertedArray: [Date] = [] var dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy" for dat in testArray { var date = dateFormatter.date(from: dat) convertedArray.append(date!) } //Approach : 1 convertedArray.sort(){$0 < $1} //Approach : 2 convertedArray.sorted(by: {$0.timeIntervalSince1970 < $1.timeIntervalSince1970}) print(convertedArray)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With