Sorting an Array by Date Value in JavaScript
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:
1 | const activities = [ |
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
):
1 | 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:
1 | 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.
tags: [“JavaScript”, “Array”, “sorting”, “date objects”]