How to Sort an Array by Date in TypeScript?

In this tutorial, I will explain how to sort an array by date in TypeScript. Sorting arrays by date is a common task in web development, especially when dealing with data such as event schedules, appointment bookings, or historical records. I will cover both ascending and descending order sorting an array in TypeScript and include practical examples.

Sort an Array by Date in TypeScript

Now, let me show you how to sort an array by date in TypeScript with some real examples. I will start with the basic array sorting.

Let’s start with a simple example. Suppose we have an array of dates representing important historical events in the USA:

const historicalEvents: string[] = [
    "1776-07-04", // Declaration of Independence
    "1865-04-09", // End of Civil War
    "1969-07-20", // Moon Landing
    "2001-09-11"  // 9/11 Attacks
];

1. Sort Array Dates in Ascending Order

To sort this array in ascending order (from the earliest to the latest date), we can use the sort method along with a custom comparator function:

const historicalEvents: string[] = [
    "1776-07-04", // Declaration of Independence
    "1865-04-09", // End of Civil War
    "1969-07-20", // Moon Landing
    "2001-09-11"  // 9/11 Attacks
];
historicalEvents.sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
console.log(historicalEvents);

In this code snippet, the comparator function converts each date string to a Date object and compares their time values. This ensures the dates are sorted correctly.

Here is the exact output in the screenshot below:

Sort an Array by Date in TypeScript

Check out Sort a Number Array in Descending Order using TypeScript

2. Sort Dates in Descending Order

For descending order (from the latest to the earliest date), simply reverse the subtraction in the comparator function:

const historicalEvents: string[] = [
    "1776-07-04", // Declaration of Independence
    "1865-04-09", // End of Civil War
    "1969-07-20", // Moon Landing
    "2001-09-11"  // 9/11 Attacks
];
historicalEvents.sort((a, b) => new Date(b).getTime() - new Date(a).getTime());
console.log(historicalEvents);

Read Sort an Array of Objects by Property in TypeScript

Sort an Array of Objects by Date in TypeScript

In real-world applications, dates are often part of more complex objects. For example, consider an array of objects representing upcoming events in New York City:

interface Event {
    name: string;
    date: string;
}

const events: Event[] = [
    { name: "New Year's Eve Ball Drop", date: "2024-12-31" },
    { name: "Thanksgiving Parade", date: "2024-11-28" },
    { name: "Fourth of July Fireworks", date: "2024-07-04" },
    { name: "Halloween Parade", date: "2024-10-31" }
];

1. Sorting Events by Date Ascending

To sort these events in ascending order by date, we use a similar approach:

interface Event {
    name: string;
    date: string;
}

const events: Event[] = [
    { name: "New Year's Eve Ball Drop", date: "2024-12-31" },
    { name: "Thanksgiving Parade", date: "2024-11-28" },
    { name: "Fourth of July Fireworks", date: "2024-07-04" },
    { name: "Halloween Parade", date: "2024-10-31" }
];
events.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
console.log(events);

Check out Search an Array of Objects by Property in TypeScript

2. Sorting Events by Date Descending

For descending order, adjust the comparator function accordingly:

interface Event {
    name: string;
    date: string;
}

const events: Event[] = [
    { name: "New Year's Eve Ball Drop", date: "2024-12-31" },
    { name: "Thanksgiving Parade", date: "2024-11-28" },
    { name: "Fourth of July Fireworks", date: "2024-07-04" },
    { name: "Halloween Parade", date: "2024-10-31" }
];
events.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
console.log(events);

Handle Date Formats

Sometimes, dates may come in different formats. TypeScript’s Date object can handle various date formats, but it’s essential to ensure consistency. If your date strings are inconsistent, consider normalizing them before sorting.

Example with Date Normalization

Suppose we have an array of events with dates in different formats:

const mixedFormatEvents: Event[] = [
    { name: "New Year's Eve Ball Drop", date: "12/31/2024" },
    { name: "Thanksgiving Parade", date: "November 28, 2024" },
    { name: "Fourth of July Fireworks", date: "2024-07-04" },
    { name: "Halloween Parade", date: "10-31-2024" }
];

We can normalize the date formats using a utility function before sorting:

function normalizeDate(dateString: string): string {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0]; // Convert to YYYY-MM-DD format
}

mixedFormatEvents.forEach(event => {
    event.date = normalizeDate(event.date);
});

mixedFormatEvents.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
console.log(mixedFormatEvents);

Check out Sort an Array Alphabetically in TypeScript

Performance Considerations

Sorting large arrays can be computationally expensive. TypeScript’s sort method uses a time complexity of O(n log n), which is efficient for most use cases. However, for very large datasets, consider optimizing your approach or using more advanced data structures.

Example with a Large Dataset

Imagine we have a large dataset of historical events in the USA:

const largeEvents: Event[] = [];
for (let i = 0; i < 100000; i++) {
    largeEvents.push({
        name: `Event ${i}`,
        date: new Date(2024, Math.floor(Math.random() * 12), Math.floor(Math.random() * 28) + 1).toISOString()
    });
}

console.time('sort');
largeEvents.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());
console.timeEnd('sort');

This example demonstrates how to measure the performance of the sorting operation using console.time.

Conclusion

In this tutorial, I have explained how to sort arrays by date in TypeScript with some examples.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.