I have list that contain various object. A few objects on this list have a date field (which basically is returned to me as a string from server, not a date object), while for others this field is null.
The requirement I have is to display objects without date at top, and those with date needs to be displayed after them sorted by date field.
Also for objects without date sorting needs to be done alphabetically.
Earlier I was using
$scope.lists.sort(function (a, b) {
return new Date(a.date.split("-")[2], a.date.split("-")[1], a.date.split("-")[0]) - new Date(b.date.split("-")[2], b.date.split("-")[1], b.date.split("-")[0]);
});
But now with null date fields this would not work. So unable to find anything, I wrote this logic:
{
var datelists=[];
var savelists =[];
$scope.lists.forEach(function (t) {
if (t.date !== null) {
datelists.push(t);
} else {
savelists.push(t);
}
});
datelists.sort(function (a, b) {
return new Date(a.date.split("-")[2], a.date.split("-")[1], a.date.split("-")[0]) - new Date(b.date.split("-")[2], b.date.split("-")[1], b.date.split("-")[0]);
});
savelists.sort(function (a, b) {
return a.name - b.name;
});
$scope.lists = [];
$scope.lists = savelists.concat(datelists);
}
I don't like this long method. I am sure there is an elegant way to do this. I would like to know what other alternatives do I have?