JavaScript: Sorting an Array of Objects by Date Property

Updated: March 7, 2023 By: Frienzied Flame Post a comment

To sort an array of objects by date property in JavaScript, we can use the Array.prototype.sort() method with a custom comparator function. The comparator function should compare the date values of the objects using the Date constructor and return a value based on the comparison.

When you want to sort in ascending date order, the comparator function will look like this:

((a, b) => new Date(a.dateProperty) - new Date(b.dateProperty)

When you want to sort in descending date order:

((a, b) => new Date(b.dateProperty) - new Date(a.dateProperty)

Examples

Sort users by account age, from newest to oldest

The code:

const users = [
  { id: 1, name: 'Sasuke Honda', joinedDateTime: '2022-01-01T12:30:00.000Z' },
  {
    id: 2,
    name: 'Ranni The Witch',
    joinedDateTime: '2021-12-31T15:45:00.000Z',
  },
  { id: 3, name: 'Wolf', joinedDateTime: '2022-02-01T09:00:00.000Z' },
  { id: 4, name: 'Sling Academy', joinedDateTime: '2024-02-01T09:00:00.000Z' },
];

users.sort((a, b) => new Date(b.joinedDateTime) - new Date(a.joinedDateTime));

console.log(users);

Output:

[
  {
    id: 4,
    name: 'Sling Academy',
    joinedDateTime: '2024-02-01T09:00:00.000Z'
  },
  { id: 3, name: 'Wolf', joinedDateTime: '2022-02-01T09:00:00.000Z' },
  {
    id: 1,
    name: 'Sasuke Honda',
    joinedDateTime: '2022-01-01T12:30:00.000Z'
  },
  {
    id: 2,
    name: 'Ranni The Witch',
    joinedDateTime: '2021-12-31T15:45:00.000Z'
  }
]

Note that the sort() method modifies the original array in place. If you want to keep the original array intact, just clone it. See this article if you aren’t familiar with this task.

Sort books by publication date, from oldest to newest

The code:

const books = [
  { title: 'The Great Gatsby', publishDate: '1925-04-10' },
  { title: 'To Kill a Mockingbird', publishDate: '1960-07-11' },
  { title: '1984', publishDate: '1949-06-08' },
];

books.sort((a, b) => new Date(a.publishDate) - new Date(b.publishDate));

console.log(books);

Output:

[
  { title: 'The Great Gatsby', publishDate: '1925-04-10' },
  { title: '1984', publishDate: '1949-06-08' },
  { title: 'To Kill a Mockingbird', publishDate: '1960-07-11' }
]

That’s it. Happy coding!