If we have an array of JavaScript objects that each contain a property of the Date
type, for example:
const events = [
{ name: 'Birthday', date: new Date('2022-04-23') },
{ name: 'Shopping', date: new Date('2022-04-17') },
{ name: 'Meeting', date: new Date('2022-04-27') },
];
How can we sort these objects by the date
property?
The Array sort() Method
We can easily do this with the Array sort()
method:
events.sort((a, b) => a.date.getTime() - b.date.getTime());
The sort method takes a callback function as an argument. It uses the value returned from this function to decide the order in which to sort the values.
If the callback result is negative, a
is sorted before b
.
If the result is positive, b
is sorted before a
.
If the result is 0
, the sort order of the two values stays the same.
This means that we can just as easily sort the array in descending order like this:
events.sort((a, b) => b.date.getTime() - a.date.getTime());
Now the result will be positive when b
is larger than a
and this will make sort()
place b first.
Note: You can also sort the array by subtracting the Date
objects directly:
events.sort((a, b) => b.date - a.date);
While this method also works, it is considerably slower than subtracting with getTime()
.
Here’s the result of a performance comparison of both methods, each executing for 1 million iterations:
Direct subtraction: 488.675ms
Subtraction with getTime(): 196.909ms
Sorting without Mutating
The sort()
method sorts the array in place, which means it gets modified. To prevent this, we can use the slice()
method to create a copy of the array for the sort:
const sortedEvents = events.slice().sort((a, b) => a.date - b.date);