Sort Object Array By Date in JavaScript
- 1 minute read
Suppose you have an object array that looks like this:
const events = [
{
date: '2021-11-24T01:02:03-07:00',
id: 0,
},
{
date: '2021-11-25T04:05:06-07:00',
id: 1,
},
{
date: '2021-11-23T07:08:09-07:00',
id: 2,
}
]
You could then use JavaScript’s built-in
array sorting method to sort by the date
key, like this:
const sortByDateDescending => (array) => {
events.sort((a, b) => {
return a.date - b.date;
});
});
The above function can be used simply by calling it and passing in the events
array, like this:
sortByDateDescending(events); // Sorts the "events" array by date, in descending order
Here is a variant of the sortByDateDescending
function that sorts the array elements by date in ascending order instead:
const sortByDateAscending => (array) => {
events.sort((a, b) => {
return b.date - a.date;
});
});
Conclusion
I hope you found this useful!
And by the way, don’t forget to replace a.date
and b.date
with the key you use for storing dates in your objects, if it’s different than date
.