7

How would I sort an array of dates in chronological order? For example I have:

var dates = [
    '03/03/2014',
    '01/03/2014',
    '02/03/2014',
    '04/03/2014'
];

sortDates = sortDate(dates);

sortDate(array){
    // ?
    returnt arraySort;
}

I'd like the resultant array to look like:

[
    '01/03/2014', 
    '02/03/2014',
    '03/03/2014', 
    '04/03/2014'
]
0

6 Answers 6

16

Assuming your date format is consistently DD/MM/YYYY:

dates.sort(function(a, b){
    var aa = a.split('/').reverse().join(),
        bb = b.split('/').reverse().join();
    return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

... otherwise you will have to compare Date objects if you require more flexibility.

Sign up to request clarification or add additional context in comments.

2 Comments

this works fine..however my date is in MM/DD/YYYY format and if i create two data with the same date then it does not work.Please help.
There are already answers in this thread that address your specific case. Notably this one - all you'd need to do is swap the order of comparison between indices 1 and 0. In fact that's a neater improvement on mine in either case.
7

Try this (feel free to ask for details) :

dates.sort(function (a, b) {
    // '01/03/2014'.split('/')
    // gives ["01", "03", "2014"]
    a = a.split('/');
    b = b.split('/');
    return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
});

Translation of the last line :

return          return
a[2] - b[2]     years comparison if year A - year B is not 0
||              or
a[1] - b[1]     months comparison if month A - month B is not 0
||              or
a[0] - b[0];    days comparison

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort.

Comments

2

Just improving @leaf answer as split works on strings so you might get error if the type of 'a' and 'b' is object.

dates.sort(function (a, b) {
        a = a.toString().split('/');
        b = b.toString().split('/');
        return a[2] - b[2] || a[1] - b[1] || a[0] - b[0];
    });

Comments

1

Please do this the easy way.
Works for dates formatted as 'dd/mm/yy' or 'dd/mm/yyyy'.

var dates = [
    '03/03/2014',
    '01/03/2014',
    '02/03/2014',
    '04/03/2014'
];

dates.sort( function(c,d){
    var rx = /(\d+)\/(\d+)\/(\d+)/;
    var a = Number(c.replace(rx, '$3$1$20000'));
    var b = Number(d.replace(rx, '$3$1$20000'));
    return a > b ? -1 : a == b ? 0 : 1; // for newer on top
    //return a < b ? -1 : a == b ? 0 : 1; // for older on top
  });

Comments

0

Digigizmo answer works!

in case: dd/mm/yyyy hh:mm:ss you can use:

list.sort(function (a, b) {
    var aa = a.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', a.substring(11, 20)),
    bb = b.substring(0, 10).split('/').reverse().join() + replaceAll(':', '', b.substring(11, 20));
    return aa < bb ? -1 : (aa > bb ? 1 : 0);
});

and replaceAll function:

function replaceAll(find, replace, str) {
  return str.replace(new RegExp(find, 'g'), replace);
}

Comments

0
let arrayDate = ["11/12/2022", "10/11/2021", "20/01/2001", "30/10/2022"];function formatFrToEn(arg){
let [day, month, year] = arg.split("/");
let newFormatDate = [month, day, year].join("/");
return newFormatDate;}let newArrayDate = arrayDate.map( x => new Date( formatFrToEn(x) ) )console.log(newArrayDate)newArrayDate = newArrayDate.sort( (a, b) => Number(a) - Number(b) )function padTo2Digits(num) {
return num.toString().padStart(2, '0');}function formatDate(date){return[padTo2Digits(date.getDate()),padTo2Digits(date.getMonth() + 1), date.getFullYear(),.join('/');newArrayDate = newArrayDate.map(x=>formatDate(x))console.log(newArrayDate)

1 Comment

Welcome to stackoverflow. Please enrich your answer with some details and avoid just sending a piece of code

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.