Computer >> Computer tutorials >  >> Programming >> Javascript

How to sort a JavaScript object list based on a property when the property is not consistent


We have an array that contains various objects. A few objects on this array have a date field (which basically is returned as a string from the server, not a date object), while for others this field is null.

The requirement is that we have 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.

Example

const sorter = ((a, b) => {
   if (typeof a.date == 'undefined' && typeof b.date != 'undefined') {
      return -1;
   }
   else if (typeof a.date != 'undefined' && typeof b.date == 'undefined') {
      return 1; }
   else if (typeof a.date == 'undefined' && typeof b.date == 'undefined') {
      return a.name.localeCompare(b.name);
   }
   else if (a.date == null && b.date != null) {
      return -1;
   }
   else if (a.date != null && b.date == null) {
      return 1;
   }
   else if (a.date == null && b.date == null) {
      return 0;
   }
   else {
      var d1 = Date.parse(a.date);
      var d2 = Date.parse(b.date);
      return d1 - d2;
   }
});