Sorting an array by multiple properties including date

Viewed 109

I want to sort an array by an enumeration, then by a number then by date. When I do it with enumeration and number it seems to work fine however when I include the date at the end it messes everything.

Here's my code:

enum myType { 
  high,
  medium,
  low
}

myArray.sort((a, b) =>
  myType[a.type] - myType[b.type] ||
  a.classification - b.classification ||
  new Date(a.time) > new Date(b.time)
    ? -1
    : 1
);

However this seems to sort the opposite meaning it sorts by type in the opposite order where low first and high last. How do we go about this?

Update: Date will get passed as this: 2017-07-02T14:59:55.711Z

1 Answers

Without knowing the style of time, you need to wrap the ternary to prevent the reading of all expressions for the ternary.

myArray.sort((a, b) =>
    myType[a.type] - myType[b.type] ||
    a.classification - b.classification ||
    (new Date(a.time) > new Date(b.time)
        ? -1
        : 1)
);

By using ISO 8601 compliant strings, you could take a string comparison with String#localeCompare.

myArray.sort((a, b) =>
    myType[a.type] - myType[b.type] ||
    a.classification - b.classification ||
    a.time.localeCompare(b.time)
);
Related