Sort an Array By Date

May 2022 | Using .sort and .getTime

const posts = [
  { slug: "third", date: new Date("2022-02-23") },
  { slug: "fourth", date: new Date("2022-01-10") },
  { slug: "first", date: new Date("2022-01-01") },
  { slug: "second", date: new Date("2022-01-05") },
]

A new list of posts sorted by date can be created like this:

// Ascending order:
const asc = posts.sort((postA, postB) => postA.date.getTime() - postB.date.getTime())
// Descending order (latest post first):
const desc = posts.sort((postA, postB) => postB.date.getTime() - postA.date.getTime())
Why use .getTime?

JavaScript implicitly coerces dates to numbers when trying to subtract one from another, so using .getTime() and subtracting numbers is more efficient.

Additionally, if you try sorting dates in typescript like dates.sort((a, z) => a - z) without using .getTime(), you may see the following errors:

The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type
The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type