0
 var array =  [{"id":"0", "stopDate":null},
               {"id":"1", "stopDate":"10/06/2014"},
               {"id":"2", "stopDate":null},
               {"id":"3", "stopDate":"09/06/2014"}];

I have array of objects as above and want to sort by stop date using underscore. I am using following function to do so.

_.sortBy(array, "stopDate"); // asc
_.sortBy(array, "stopDate").reverse(); //desc

Above method sorts the date value properly but ignores null. So the output for asc is coming out to be

var actual=  [{"id":"0", "stopDate":null},
              {"id":"3", "stopDate":"09/06/2014"},
              {"id":"2", "stopDate":null},
              {"id":"1", "stopDate":"10/06/2014"}];

But I am expecting null to be grouped together and should appear one after other.

var expected=  [{"id":"0", "stopDate":null},
                {"id":"2", "stopDate":null},
                {"id":"3","stopDate":"09/06/2014" },
                {"id":"1", "stopDate":"10/06/2014"}];
Anonymous Me
  • 1,108
  • 2
  • 9
  • 26

1 Answers1

2

Above method sorts the date value properly

Not really. A lexical string comparison on the format DD/MM/YYYY hardly will return the expected results.

but ignores "--"

There are no "--" values in your objects, there only are null values. And since null values are neither greater nor smaller than (non-numeric) strings (you can try in console, it always yields false), they are considered equal - which does however make an inconsistent comparison.

What you should do instead is parse those date strings into properly comparable timestamps, and the null values into either -Infinity or +Infinity so that they compare with the timestamps as expected:

_.sortBy(array, function(d) {
    if (d.stopDate == null) return -Infinity;
    var parts = d.stopDate.split("/");
    return (new Date(+parts[2], parts[1]-1, +parts[0])).getTime();
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375