Learn how to sort an array of items by date value in JavaScript.
If you have an array of objects like the one below, 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') }
]
and you want to sort those activities by the date
property, you can use the sort()
method of Array
. The sort()
method takes a callback function as a parameter, which in turn takes two objects contained in the array (referred to as a
and b
):
const sortedActivities = activities.sort((a, b) => b.date - a.date)
In this example, when the callback function returns a positive value, it indicates that object b
should precede object a
in the sorting order. Conversely, returning a negative value would do the opposite.
The sort()
method not only returns a new sorted array, but it also sorts the original array in place. If you want to preserve the original array and create a sorted copy, you can use the slice()
method to create a copy of the array prior to sorting:
const sortedActivities = activities.slice().sort((a, b) => b.date - a.date)
Remember to implement this technique whenever you need to sort an array of objects by date value in JavaScript.