Coding Ref

Sort dates in JavaScript

Sort an array of Objects by Date value in JavaScript

To sort an array of objects by date value, use the sort() method on the array.

Here's an example with some objects that we want to sort.

To sort dates by value in JavaScript, the dates must be a Date Object. See below for how to convert string dates to a Date Object, so that they can be sorted.
const birthdays = [
  { title: "John", date: new Date("2018-06-28") },
  { title: "Taylor", date: new Date("2019-06-10") },
  { title: "Sam", date: new Date("2016-06-22") },
];

We want to sort these birthdays by the date property. We use the sort() Array method, which takes a callback function.

The function takes two objects as parameters, which we call a and b. We compare the two to determine the sort order.

// ⬆️ Sort in descending order (recent to old)
const sortedBirthdays = birthdays.sort((a, b) => b.date - a.date);

The function compares the two dates and returns a positive value, indicating that b takes precedence over a. Returning a negative value indicates that a takes precedence over b.

The above sort() will sort the object in a descending order, starting with the most recent date and ending with the oldest one..

The below sort() will sort them in ascending order, starting with the oldest date and ending with the most recent one.

// ⬇️ sort in ascending order (old to recent)
const sortedBirthdays = birthdays.sort((a, b) => a.date - b.date);

Prevent the original array from being sorted

The sort() method returns a new sorted array, but also sorts the original array. Both sortedBirthdays and birthdays are now sorted.

If you only want a new sorted array, while keeping the original array unsorted, use the slice() method to create a copy of the array prior to sorting.

const sortedBirthdays = birthdays.slice().sort((a, b) => b.date - a.date);

Dates are strings

If your dates are strings and not Date objects, use the following code, which will convert the strings to Dates.

// ⬆️ Sort in descending order (high to low)
const sortedBirthdays = birthdays.sort(function (a, b) {
  return new Date(b.date) - new Date(a.date);
});

// ⬇️ sort in ascending order (low to high)
const sortedBirthdays = birthdays.sort(function (a, b) {
  return new Date(a.date) - new Date(b.date);
});

Conclusion

To sort an array of objects by date value, use the sort() method on the array.

You'll also like

Related tutorials curated for you

    Sort dates in JavaScript

    ReferenceError: document is not defined in JavaScript

    Returning multiple values in JavaScript

    Cannot use import statement outside a module in JavaScript

    Could not find module '@angular-devkit/build-angular'

    Unexpected token u in JSON at position 0 Error