How to sort an array by date value in JavaScript
New Course Coming Soon:
Get Really Good at Git
Find out how to sort an array of items by date value in JavaScript
Say you have an array of objects like this, which contains a set of date objects:
const activities = [
{ title: 'Hiking', date: new Date('2019-06-28') },
{ title: 'Shopping', date: new Date('2019-06-10') },
{ title: 'Trekking', date: new Date('2019-06-22') }
]
You want to sort those activities by the date
property.
You can use the sort()
method of Array
, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a
and b
):
const sortedActivities = activities.sort((a, b) => b.date - a.date)
When we return a positive value, the function communicates to sort()
that the object b
takes precedence in sorting over the object a
. Returning a negative value will do the opposite.
The sort()
method returns a new sorted array, but it also sorts the original array in place. Thus, both the sortedActivities
and activities
arrays are now sorted. One option to protect the original array from being modified is to use the slice()
method to create a copy of the array prior to sorting, as follows:
const sortedActivities = activities.slice().sort((a, b) => b.date - a.date)
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X