# Sorting Based on Multiple Criteria

In many applications, you may need to sort data based on multiple criteria or "keys." For example, you may need to sort a list of tickets by **status**, then by **due date**, and finally by **due time**. In this article, we’ll show you how to achieve multiple-level sorting using JavaScript.

Scenario

Let’s say you have a list of tickets, and each ticket has three important attributes:

* **Status**: The current status of the ticket (e.g., OPEN, IN\_PROGRESS).
* **Due Date**: The date by which the ticket is expected to be completed.
* **Due Time**: The specific time on the due date.

You want to sort these tickets based on:

1. **Status**: Tickets should be ordered from the most urgent to the least urgent.
2. **Due Date**: Tickets with the soonest due date should come first.
3. **Due Time**: If two tickets share the same due date, they should be further sorted by their due time, with the latest time coming first.

Code Implementation

Here’s how you can implement this multi-level sorting in JavaScript:

<pre class="language-javascript"><code class="lang-javascript"><strong>function sortTickets(tickets) {
</strong>  const statusOrder = {
    OPEN: 1,
    REOPENED: 2,
    IN_PROGRESS: 3,
    ON_HOLD: 4,
    COMPLETED: 5,
    CANCEL: 6
  };

  return tickets.sort((a, b) => {
    // Compare by status
    if (statusOrder[a.status] !== statusOrder[b.status]) {
      return statusOrder[a.status] - statusOrder[b.status];
    }

    // Compare by dueDate in ascending order
    const dateA = new Date(a.dueDate).getTime();
    const dateB = new Date(b.dueDate).getTime();
    if (dateA !== dateB) {
      return dateA - dateB;
    }

    // Compare by dueTime in descending order
    const timeA = convertToMinutes(a.dueTime);
    const timeB = convertToMinutes(b.dueTime);
    return timeB - timeA;
  });
}

<strong>function convertToMinutes(time) {
</strong>  const [hours, minutes] = time.split(':').map(Number);
  return hours * 60 + minutes;
}

</code></pre>

#### Explanation

1. **Sorting by Status**: The `statusOrder` object defines a numerical order for the ticket statuses. Tickets are sorted based on their status, from most urgent (OPEN) to least urgent (CANCEL).
2. **Sorting by Due Date**: After sorting by status, tickets are further sorted by their `dueDate`. The `new Date(a.dueDate)` converts the due date string into a Date object for accurate comparison, ensuring tickets with earlier due dates come first.
3. **Sorting by Due Time**: If two tickets have the same due date, they are further sorted by `dueTime`. The `convertToMinutes` function converts the time string into minutes, allowing us to compare the times directly. The result is that tickets with later due times appear first.

#### Example Usage

Here’s an example of how the sorting function works:

```javascript
const tickets = [
  { id: 1, status: 'OPEN', dueDate: '2025-01-06', dueTime: '14:30' },
  { id: 2, status: 'IN_PROGRESS', dueDate: '2025-01-06', dueTime: '09:00' },
  { id: 3, status: 'CANCEL', dueDate: '2025-01-07', dueTime: '16:00' },
  { id: 4, status: 'OPEN', dueDate: '2025-01-05', dueTime: '12:00' },
  { id: 5, status: 'REOPENED', dueDate: '2025-01-06', dueTime: '14:00' }
];

const sortedTickets = sortTickets(tickets);
console.log(sortedTickets);

```

Output

```javascript
[
  { id: 1, status: 'OPEN', dueDate: '2025-01-06', dueTime: '14:30' },
  { id: 5, status: 'REOPENED', dueDate: '2025-01-06', dueTime: '14:00' },
  { id: 2, status: 'IN_PROGRESS', dueDate: '2025-01-06', dueTime: '09:00' },
  { id: 4, status: 'OPEN', dueDate: '2025-01-05', dueTime: '12:00' },
  { id: 3, status: 'CANCEL', dueDate: '2025-01-07', dueTime: '16:00' }
]

```

#### Conclusion

In situations where you need to sort data based on multiple criteria, you can use this method to chain sorting conditions. By sorting first by one key (e.g., status), and then by additional keys (e.g., due date and due time), you can ensure that the data is ordered exactly as needed.

This approach is highly useful when working with complex datasets in applications like task management, project tracking, or event scheduling.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wisdom.gitbook.io/gyan/javascript/sorting-based-on-multiple-criteria.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
