Wisdom
  • Welcome
  • core
    • Flyway
    • Bean Validation
    • Lombok
    • Webclient
      • Generic Webclient Api
      • SSL Certificate
    • Application Event Publisher
    • REST API's Design
      • Http Methods and Status Codes
      • Resource Naming and URL Structure
      • Request / Response Design
      • Versioning Strategies
      • Filtering and Searching In API
    • Spring Boot Mail Integration
      • Sendgrid
    • Template Engines
      • Java Template Engine [JTE]
  • security
    • Complete Guide to URL Matchers in Spring Security: Types, Examples, Pros, Cons, and Best Use Cases
    • Passwordless Login With Spring Security 6
      • Spring Security OneTimeToken
        • One Time Token with default configuration
        • One Time Token with custom configuration
        • One Time Token With Jwt
  • others
    • How to Integrate WhatsApp for Sending Messages in Your Application
  • java
    • Interview Questions
      • Constructor
      • Serialization
      • Abstract Class
    • GSON
      • Type Token
      • Joda Datetime Custom Serializer and Deserializer
  • Nginx
    • Core Concepts and Basics
    • Deep Dive on NGINX Configuration Blocks
    • Deep Dive on NGINX Directives
    • Deep Dive into Nginx Variables
    • Nginx as a Reverse Proxy and Load Balancer
    • Security Hardening in NGINX
    • Performance Optimization & Tuning in NGINX
    • Dynamic DNS Resolution in Nginx
    • Advanced Configuration & Use Cases in NGINX
    • Streaming & Media Delivery in NGINX
    • Final Configuration
  • Angular
    • How to Open a PDF or an Image in Angular Without Dependencies
    • Displaying Colored Logs with Search Highlighting in Angular 6
    • Implementing Auto-Suggestion in Input Field in Angular Template-Driven Forms
    • Creating an Angular Project Using npx Without Installing It Globally
    • Skip SCSS and Test Files in Angular with ng generate
  • Javascript
    • When JavaScript's Set Falls Short for Ensuring Uniqueness in Arrays of Objects
    • Demonstrating a Function to Get the Last N Months in JavaScript
    • How to Convert Numbers to Words in the Indian Numbering System Using JavaScript
    • Sorting Based on Multiple Criteria
  • TYPESCRIPT
    • Using Omit in TypeScript
Powered by GitBook
On this page
  1. Javascript

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:

function sortTickets(tickets) {
  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;
  });
}

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

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:

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

[
  { 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.

PreviousHow to Convert Numbers to Words in the Indian Numbering System Using JavaScriptNextUsing Omit in TypeScript

Last updated 5 months ago