Sort an array by date in JavaScript

Written by Tom Wells on

This snippet includes sorting an array of objects by date, using the sort() method with performance considerations.

Simple solution

This is a simple solution that uses the sort() method to sort the array while using new Date() to parse the string. This is not the most performant solution, but it is the simplest. For a performant solution, see below.

const arrayOfDates = [
  '2021-01-01',
  '2021-01-09',
  '2021-01-04',
  '2021-01-12'
]

arrayOfDates.sort((a, b) => {
  return new Date(a) - new Date(b)
})

This will sort the dates into ascending order. To sort in descending order, replace return new Date(a) - new Date(b) with return new Date(b) - new Date(a).

Sometimes, however, you may want to keep the original array. Using sort() on an array will sort the original array, so to retain the original array and sort the data in a new array, use array.slice().sort():

const arrayOfDates = [
  '2021-01-01',
  '2021-01-09',
  '2021-01-04',
  '2021-01-12'
]

// Sort the array in ascending order, retaining the original array
const sortedArray = arrayOfDates.slice().sort((a, b) => {
  return new Date(a) - new Date(b)
})

And finally, you may also want to sort an array of objects by date:

// Array of objects containing a `date` property
const arrayOfDates = [
  {
    id: '1',
    date: '2021-01-01'
  },
  {
    id: '2',
    date: '2021-01-09'
  },
  {
    id: '3',
    date: '2021-01-04'
  },
  {
    id: '4',
    date: '2021-01-12'
  }
]

// Sort the array of objects in ascending order, retaining the original array
arrayOfDates.slice().sort((a, b) => {
  return new Date(a.date) - new Date(b.date)
})

Performant solution

For better performance, the dates should be either in ISO date & time format or an existing date object. That way, you don't need to parse the date string every time you sort the array:

// Array of ISO dates
const arrayOfDates = [
  '2021-01-01T00:00:00Z',
  '2021-01-09T00:00:00Z',
  '2021-01-04T00:00:00Z',
  '2021-01-12T00:00:00Z'
]

const sortedDatesAsc = arrayOfDates.slice().sort((a, b) => {
  return a > b ? 1 : a < b ? -1 : 0
})

const sortedDatesDesc = arrayOfDates.slice().sort((a, b) => {
  return a > b ? -1 : a < b ? 1 : 0
})

In this case you're simply comparing the dates which is much more performant. Thanks to this stackoverflow answer for the inspiration.

For more useful JavaScript code snippets, check out the JavaScript category page.