Sort Arrays by Date in TypeScript

When I was working on a TypeScript project recently, I had to display a list of events sorted by their dates. I used .sort() to arrange them, but it didn’t work as expected because the dates were a mix of strings and Date objects.

To fix this, I converted all the date values to Date objects inside the sort function and compared them using .getTime().

In this TypeScript tutorial, I will explain how to sort arrays by date in TypeScript, whether your dates are in string format or actual Date objects.

Why is Sorting Dates Important in TypeScript?

Sorting dates is essential for presenting data in a meaningful and user-friendly way. Imagine a task manager app showing tasks in a random order; it would be chaotic and hard to use. By sorting tasks by their due dates, users can easily see which tasks are due soon and prioritize accordingly. This tutorial will guide you through the process of sorting dates in TypeScript, ensuring your data is always presented in a logical order.

Check out: Format Dates in TypeScript

Setting Up the TypeScirpt Project

To get started, let’s set up a simple TypeScript project. If you haven’t already, you can install TypeScript using npm:

npm install -g typescript

Create a new folder for your project and initialize a new TypeScript project:

mkdir sort-dates
cd sort-dates
tsc --init

Now, create an index.ts file where we will write our code.

Basic Array Sorting in TypeScript

Let’s start with a basic example of sorting an array of dates. Consider an array of event objects, each with a name date property:

interface CalendarEvent {
  name: string;
  date: Date;
}

const events: CalendarEvent[] = [
  { name: "Independence Day Parade", date: new Date("2025-03-04") },
  { name: "Thanksgiving Dinner", date: new Date("2025-04-28") },
  { name: "New Year's Eve Party", date: new Date("2025-02-31") },
  { name: "Labor Day BBQ", date: new Date("2025-09-02") },
];

events.forEach(event => {
  console.log(`${event.name} - ${event.date.toDateString()}`);
});

Output:

Sort Arrays by Date in TypeScript

We can use this method to sort this array by date. The sort method in JavaScript and TypeScript sorts the elements of an array in place and returns the sorted array. By default, the sort method sorts the elements as strings. However, we need to provide a comparison function to sort by date.

Check out: Compare Dates Without Time in TypeScript

Sorting Date by getTime() in TypeScript

Here’s how you can sort the events array by date:

events.sort((a, b) => a.date.getTime() - b.date.getTime());

After Sorting:

Sort Array Date values in TypeScript

In this compare function, a.date.getTime() and b.date.getTime() convert the date objects to their respective time values (milliseconds since January 1, 1970). The subtraction operation sorts the dates in ascending order.

Detailed Example to Sort Date Array in TypeScript

Let’s expand our example to include more details and USA-specific names. Suppose we have an array of tasks with due dates, and we want to sort them in ascending order.

interface Task {
  title: string;
  dueDate: Date;
}

const tasks: Task[] = [
  { title: "File Taxes", dueDate: new Date("2025-04-15") },
  { title: "Attend Conference in New York", dueDate: new Date("2025-05-20") },
  { title: "Submit Project Report", dueDate: new Date("2025-03-31") },
  { title: "Vacation in California", dueDate: new Date("2025-07-10") },
];

tasks.forEach(task => {
  console.log(`${task.title} - ${task.dueDate.toDateString()}`);
});

Output:

TypeScript Sort Arrays by Date

To sort these tasks by their due dates, we use the same sort method with a compare function:

tasks.sort((a, b) => a.dueDate.getTime() - b.dueDate.getTime());

After sorting of arrays:

Sort date array in typescript

After sorting, the tasks array will be ordered by their due dates.

Check out: Calculate Yesterday’s Date in TypeScript

Handling Different Date Formats

In real-world applications, dates might come in different formats. It’s essential to handle these formats correctly to ensure accurate sorting. Let’s consider an example where dates are provided as strings:

interface Meeting {
  topic: string;
  date: string; // Date as string
}

const meetings: Meeting[] = [
  { topic: "Board Meeting", date: "2025-02-15" },
  { topic: "Team Outing", date: "2025-06-25" },
  { topic: "Client Presentation", date: "2025-01-10" },
  { topic: "Annual General Meeting", date: "2025-12-01" },
];

To sort these meetings by date, we need to convert the date strings to Date objects within the compare function:

meetings.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime());

This ensures that the date strings are correctly parsed and compared.

Output:

TypeScript Sort Arrays in decending order by Date

Sorting in Descending Order

Sometimes, you might need to sort dates in descending order. To achieve this, simply reverse the subtraction operation in the compare function:

tasks.sort((a, b) => b.dueDate.getTime() - a.dueDate.getTime());

Output:

Sort Array Dates in Descending Order in TypeScript

This will sort the tasks array in descending order by due date.

Check out: Create a Date from Year, Month, and Day in TypeScript

Using TypeScript Utility Functions

For better code organization and reusability, you can create a utility function to sort arrays by date. Here’s an example of a reusable function:

function sortByDate<T>(array: T[], key: keyof T): T[] {
  return array.sort((a, b) => new Date(a[key] as any).getTime() - new Date(b[key] as any).getTime());
}

You can use this function to sort any array of objects by a date property:

const sortedTasks = sortByDate(tasks, "dueDate");
const sortedMeetings = sortByDate(meetings, "date");

Conclusion

In this tutorial, we learned how to sort arrays by date in TypeScript, handling string dates and Date objects effectively. We saw how converting date strings to Date objects inside the sort function and comparing their timestamps using .getTime() helps achieve accurate sorting. We also learned to sort dates in ascending and descending order with straightforward code.

By following the above methods, you can sort your data by date and avoid unexpected issues caused by inconsistent formats.

You may like to read:

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.