How to Sort an Array of Objects by Date in JavaScript

We often need to sort lists of data by their date.

We'll use the sort() function to do this. Here's a simple guide:

How to

First, let's review the code for sorting the array in ascending order, where we sort dates from the earliest to the latest:

const events = [
  { name: "Event 1", date: "2024-03-25" },
  { name: "Event 2", date: "2023-12-31" },
  { name: "Event 3", date: "2024-01-01" }
];

// Sort to compare dates for ascending order
const sorted = events.sort((a, b) => new Date(a.date) - new Date(b.date));
// For descending order just reverse the order of the elements
// Example: events.sort((a, b) => new Date(b.date) - new Date(a.date));

console.log(sorted);

You only need to flip the logic to sort in descending order.

So why does this work?

Inside the function, we're turning the date strings of a and b into Date objects. This lets us work with them as dates, not just text. new Date(a.date) creates a date object from the date of event a, and new Date(b.date) does the same for event b. Subtracting one date from another gives us a difference in milliseconds. If a is earlier than b, this will be a negative number. If a is later, it will be positive. The .sort() method uses this difference to decide the order.

Notes

This guide uses date strings in the "YYYY-MM-DD" format because it works well in JavaScript. If your dates are in a weird format, you might need to change how you handle them. Or add a step to clean your dates first.

JavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.