1

I have a problem to sort my object arrays by Date values. I found many questions that other users asked before, I went through all possible solutions and I still did not get solution for my sorting problem. I created two different arrays to test sort function too but still could not get dates in correct order. Here is my data:

[Object { eventDate="12/12/2016",  display_order="5"},Object { eventDate="12/12/2016",  display_order="3"}]

[Object { eventDate="04/21/2016",  display_order="3"},Object { eventDate="04/21/2016",  display_order="1"}]

I used this logic to sort my data by date values:

entries.sort(function(a,b){
    var i = new Date(a.eventDate);
    var j = new Date(b.eventDate);
    return i-j;
});

My data still did not sort in correct order using this function. Then I also tried to sort my array that looks like this:

var dates = Object.keys(groupedByDate);

console.log(dates)

This is output for variable dates: ["12/12/2016", "04/21/2016"]

Then I tried to do this:

dates.sort(function(a, b) {
    a = new Date(a.dates);
    b = new Date(b.dates);
    return a>b ? -1 : a<b ? 1 : 0;
});

My output still did not sort my dates in correct order. I'm not sure am I doing something wrong or something else could be a problem in this case. If anyone can help please let me know. Thanks.

2
  • I assume you want to sort it in ascending order? Your sort works for me but it orders it in descending order.... Where you also expecting only dates as the output? Commented Apr 7, 2016 at 13:51
  • I think your first sort function is correct but the datestring for the Date constructor is not. You should check if the Date instances are constructed correctly. Commented Apr 7, 2016 at 13:53

5 Answers 5

1

The answers here are on the right track but you should never use the Date constructor, or Date.parse, to parse strings. Use a library and pass the format, or write a simple function, e.g.

function parseMDY(s) {
  var b = s.split('/');
  return new Date(b[2],b[0]-1,b[1]);
}

document.write(parseMDY('4/30/2016'));

So now you have:

entries.sort(function(a,b) {
  return parseMDY(a) - parseMDY(b);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I used getMilliseconds(), how do we sort milliseconds ? Say 'asc' or 'desc' order
@Gel— getMilliseconds gets the decimal milliseconds of the second, so you'd likely get random sorting. If you want the time value, use getTime.
1

Sort dates using Date.getTime() function (by number of milliseconds):

dates.sort(function(a, b) {
    a = (new Date(a.dates)).getTime();
    b = (new Date(b.dates)).getTime();
    return a - b;
});

4 Comments

Don't bother with the ternaries and just return a - b.
Another way to get .getTime is to simply multiply the date by 1. E.g. (new Date())*1
It's pretty much the same as it is. Date objects should get coerced to numbers when used with -.
returning just a - b works fine! Thank you @FrédéricHamidi
1

You could split the date and sort with the parts.

var array = [{ eventDate: "12/12/2016", display_order: "5" }, { eventDate: "12/12/2016", display_order: "3" }, { eventDate: "04/21/2016", display_order: "3" }, { eventDate: "04/21/2016", display_order: "1" }];

array.sort(function (a, b) {
    var aa = a.eventDate.split('/'),
        bb = b.eventDate.split('/');
    return aa[2] - bb[2] || aa[0] - bb[0] || aa[1] - bb[1];
});

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

Comments

1

Seems there is an issue in the json you pasted.{ eventDate="12/12/2016", display_order="3"}.Instead of = it has to be : Assuming you have correct json format the below solutions can be useful

var array = [{ eventDate:"12/12/2016",  display_order:"5"}, 
                { eventDate:"12/12/2016",  display_order:"3"},
                { eventDate:"04/21/2016",  display_order:"3"},
                { eventDate:"04/21/2016",  display_order:"1"}];

// Generic solution
var sortedArray = array.sort(function(a,b) { 
    return new Date(a.eventDate).getTime() - new Date(b.eventDate).getTime() 
});


// Solution using ternary operator
var l =array.sort(function(a,b){
  return a.eventDate>b.eventDate ? -1 : a.eventDate<b.eventDate ? 1 : 0;
});

Demo

Comments

0

So I tried all answers above, some of them gave me close but not fully solution for my case. So I just tried to combine and this is correct solution for my problem:

dates.sort(function(a, b) {
    return new Date(a).getTime() - new Date(b).getTime();
});

If I tried to return just A and B, that worked for one record, but then when I switch user in my onChange drop down I was getting reverse dates again. So solution above with new Date() and getTime() works fine. Thank you all for your help!

1 Comment

Do not parse strings with the Date constructor or Date.parse (they are equivalent for parsing). The format in the OP is not supported by the language specification (which is poorly implemented anyway), always manually parse strings. You can use a library, but in this case you just need a 2 line function to do the job. In this case you can just reformat the strings as ISO-8601 dates and compare the strings or create Date objects.

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.