I have an array of timestamps or strings that are of this format - day–month–year.
e.g
['03-11-2018', '04-12-2018', '10-01-2017', '10-12-2017']
And I want to sort them chronologically so the above array would become [ '10-01-2017', '10-12-2017', '03-11-2018', '04-12-2018' ]
I am aware that you can use moment.js
to do this but I want to write this by hand without using any 3rd lib.
Here is my attempt:
function sortTimestamp(array) {
array.sort((time1, time2) => {
const [day1, month1, year1] = time1.split('-')
const [day2, month2, year2] = time2.split('-')
return year2 > year1
? -1
: year2 < year1
? 1
: month2 > month1
? -1
: month2 > month1
? 1
: day2 > day1
? -1
: 1
})
}
It works ok but it is not really readable and it is a very imperative approach. I wonder if there is a better way to do it and also ideally it can be extended to support that other date formats e.g. month–day–year.
CodePudding user response:
An alternative is to specify with extra arguments what the format is (regex) and how it should be reordered to ISO-style YYYYMMDD format. Then the function can perform that replacement and do a lexical sort:
function sortTime(array, regex, iso) {
let fmt = time => time.replace(regex, iso);
return array.sort((time1, time2) =>
fmt(time1).localeCompare(fmt(time2)));
}
// demo
let dates = ['03-11-2018', '04-12-2018', '10-01-2017', '10-12-2017'];
let result = sortTime(dates, /(..)-(..)-(....)/, "$3$2$1");
console.log(result);
So if the input should be interpreted as mm-dd-yyyy instead of dd-mm-yyyy, then make the third argument "$3$1$2" instead of "$3$2$1".
CodePudding user response:
It's a little simpler using subtraction rather than nested ternaries.
function sortTimestamp(array) {
array.sort((time1, time2) => {
const [day1, month1, year1] = time1.split('-')
const [day2, month2, year2] = time2.split('-')
return year1 - year2 || month1 - month2 || day1 - day2;
})
}
CodePudding user response:
You can first convert them to Date objects then use the getTime functionality to compare for sorting. A similar question was answered here
const dates = ['03-11-2018', '04-12-2018', '10-01-2017', '10-21-2017']
sortedDates = dates.sort((a,b)=>{
const dateA = new Date(a)
const dateB = new Date(b)
//change the comparison sign for required orde
return dateA.getTime() < dateB.getTime()
? 1
: -1
})
console.log(sortedDates)
CodePudding user response:
Similar to Craques answer, but added both ASC, DESC sorting using the getTime method
ASC:
dates.sort((a,b) => new Date(a).getTime() - new Date(b).getTime())
DESC:
dates.sort((a,b) => new Date(b).getTime() - new Date(a).getTime())