About Me 👈

Sorting by Date in JavaScript

How to sort an array of objects by date in JavaScript.

javascripttutorial

Created on November 11, 2019. Last updated on November 16, 2019.

Suppose you have a JavaScript object literal representing a blog post like this:

{
    title: 'Why My Income is Not Taxable',
    author: 'Patriotic Grandpa',
    description: 'Don\'t tread on me.',
    content: '...',
    date: 'Nov 12 2019 12:00:00 GMT-0500',
    updatedDate: 'Nov 18 2019 12:00:00 GMT-0500'
}

Now, imagine you have several of these blog posts in an array called posts. (To check that, pass posts to the Array.isArray function.)

Descending Order

We can sort the posts in descending order by, say, the date with:

posts.sort((a, b) => Date.parse(b.date) - Date.parse(a.date))

Ascending Order

To sort in ascending order, we simply switch a and b:

posts.sort((a, b) => Date.parse(a.date) - Date.parse(b.date))

Explanation

The sort function used is an in-place sort. We passed an anonymous compareFunction to it, following MDN's implementation instructions. The Date.parse function returns the Unix time in milliseconds of a given string. See more on Date.parse on MDN.

You may be wondering about the subtraction. That has to do with following the aforementioned compareFunction implementation instructions. Note that the compareFunction can return three possibilities:

  • A negative number, meaning that a should come before b.
  • Zero, meaning that a and b are the same, and therefore there is no reason to sort one before the other—they stay in their original order.
  • A positive number, meaning that b should come before a.

Beware, however, if the date string is not formatted properly, then Date.parse will return NaN.