Sort object with custom date format

Question

Help please me with sorting. I have to sort object with custom string date

var object = [{
  name: "something",
  date: "23.12.2016"
},
{
  name: "something2",
  date: "19.12.2016"
}]

how sort object like this? I already tried with sort function return new Date(a.date) - new Date(b.date); but had nothing it doesn't work Thanks !


Show source
| javascript   | sorting   2017-01-06 12:01 3 Answers

Answers to Sort object with custom date format ( 3 )

  1. 2017-01-06 12:01

    You could split the date and rearrange it as iso date and sort by string with localeCompare.

    var object = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }];
    
    object.sort(function (a, b) {
        var aa = a.date.split('.'),
            bb = b.date.split('.');
      
        return [aa[2], aa[1], aa[0]].join('-').localeCompare([bb[2], bb[1], bb[0]].join('-'));
    });
    
    console.log(object);

    You could use as well String#replace for reordering the string.

    var object = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }];
    
    object.sort(function (a, b) {
        var aa = a.date.replace(/(..).(..).(....)/, '$3-$2-$1'),
            bb = b.date.replace(/(..).(..).(....)/, '$3-$2-$1');
    
        return aa.localeCompare(bb);
    });
    
    console.log(object);

  2. 2017-01-06 13:01

    The solution using Date.parse() and String.prototype.replace() functions(to sort by timestamps):

    var date_objects = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }];
    
    date_objects.sort(function(a,b){
        return Date.parse(a.date.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, '$3-$2-$1'))
                - Date.parse(b.date.replace(/^(\d{2})\.(\d{2})\.(\d{4})$/, '$3-$2-$1'))
    });
    
    console.log(date_objects);

  3. 2017-01-06 13:01

    Out of curiosity, I tried a variation about Nina Scholz's answer, maybe it's faster, maybe not. I find reformatting the date quite obvious, but it's also time-consuming. In my version the duplicate indices are probably a problem, but as you stated that the format is zero-padded, this will work:

    var object = [{ name: "something", date: "23.12.2016" }, { name: "something2", date: "19.12.2016" }];
    
    object.sort(function (a, b) {
        return (a.date[6] - b.date[6]) 
            || (a.date[7] - b.date[7])
            || (a.date[8] - b.date[8])
            || (a.date[9] - b.date[9])
            || (a.date[3] - b.date[3])
            || (a.date[4] - b.date[4])
            || (a.date[0] - b.date[0])
            || (a.date[1] - b.date[1]);
    });
    
    console.log(object);

Leave a reply to - Sort object with custom date format

◀ Go back