Sorting means putting things in order and making them more organized. We use dates in a lot of scenarios like building a task scheduler, managing events, or displaying a timeline. Therefore, often, we may be required to sort dates in JavaScript. In this article, we will explore how to sort an array of objects by date, allowing us to manage our data more accurately.
How to Sort by Date in JavaScript?
JavaScript has a built-in Sort() method to sort data objects. A date in an object can be in the form of a string or as a Date object.
Here’s the demonstration:
const myObject = {
eventName: "Sample Event",
eventDate: "2022-03-20" // Date represented as a string
};
const myObject = {
eventName: "Sample Event",
eventDate: new Date("2022-03-20") // Date represented as a Date object
};
Whether the date is initially stored as a string or as a Date object, We may often need to convert it into a Date object to perform various operations on it.
Next, we will use a compareFunction inside the sort() method.
CompareFunction is written as :
array.sort(compareFunction);
This compareFunction takes two parameters in it. Let it be a and b. These are the two values we are comparing. It returns a negative, zero, or positive value based on arguments passed.
If ‘a’ should be placed before ‘b’ it returns a negative value, in the case of a positive value ‘a’ is placed after ‘b’, and zero is returned if ‘a’ and ‘b’ are of the same order.
Let’s explore various methods for sorting dates in JavaScript.
1) Sort() Method with Date Objects
This is a simple approach by using a built-in sort() method with Date objects. The sort() method compares Date objects directly and sorts the array in ascending order. Let’s understand through an example to sort by date:
// Sample data representing employees with names and dates of joining
const employeesData = [
{ name: 'John Doe', joinDate: '2022-03-15' },
{ name: 'Alice Smith', joinDate: '2023-01-10' },
{ name: 'Bob Johnson', joinDate: '2022-06-22' }
];
Here as we can see initially our dates are in string form, so we have to convert these to Date objects because the sort() Method works on Date objects.
The syntax for creating a Date object is:
let dateX = new Date(x.joinDate); Here a new Date() constructor is used. Let's apply this in our example: // Convert date strings to Date objects and then sort the array employeesData.sort((a, b) => new Date(a.joinDate) - new Date(b.joinDate)); // Display the sorted array based on the 'joinDate' property console.log(employeesData);
Output:
[
{ name: 'John Doe', joinDate: '2022-03-15' },
{ name: 'Bob Johnson', joinDate: '2022-06-22' },
{ name: 'Alice Smith', joinDate: '2023-01-10' }
]
Hence our dates are successfully sorted using the sort() method.
we returned -1,1 or 0 based on comparisons. More appropriately we returned -1 if ‘a’ should be placed before ‘b’,1 if ‘a’ should be placed after ‘b’, and 0 if no change.
2) Using getTime() Method
In this method, sorting is done by numeric representations of dates. The numeric representations are obtained by the getTime() method. We will use the sort() method along with getTime() to sort dates. Let’s consider an example:
// Sample data representing employees with names and dates of joining const employeesData = [ { name: 'John Doe', joinDate: new Date('2022-03-15') }, { name: 'Alice Smith', joinDate: new Date('2023-01-10') }, { name: 'Bob Johnson', joinDate: new Date('2022-06-22') } ]; // Sorting the array based on the 'joinDate' property employeesData.sort((a, b) => a.joinDate.getTime() - b.joinDate.getTime()); // Display the sorted array based on the 'joinDate' property console.log(employeesData);
Here already our dates are as date objects. We got numeric representations by getTime() and then used a compareFunction inside sort() method.
Output:
[
{ name: 'John Doe', joinDate: 2022-03-15T00:00:00.000Z },
{ name: 'Bob Johnson', joinDate: 2022-06-22T00:00:00.000Z },
{ name: 'Alice Smith', joinDate: 2023-01-10T00:00:00.000Z }
]
3) Using a Custom Sorting Function
In this approach, we will define a custom sorting function. We can design the function as we want, and then we will pass it as an argument for the sort() method.
Let’s take an example where we want to sort decreasingly by date:
// Sample data representing employees with names and dates of joining const employeesData = [ { name: 'John Doe', joinDate: new Date('2022-03-15') }, { name: 'Alice Smith', joinDate: new Date('2023-01-10') }, { name: 'Bob Johnson', joinDate: new Date('2022-06-22') } ]; // Custom sorting function for descending order const sortByJoinDateDescending = (a, b) => { return b.joinDate - a.joinDate; }; // Sorting the array based on the 'joinDate' property in descending order employeesData.sort(sortByJoinDateDescending); //Display the output console.log(employeesData);
Output:
[
{ name: 'Alice Smith', joinDate: 2023-01-10T00:00:00.000Z },
{ name: 'Bob Johnson', joinDate: 2022-06-22T00:00:00.000Z },
{ name: 'John Doe', joinDate: 2022-03-15T00:00:00.000Z }
]
Here we can see that we created our custom function sortByJoinDateDescending to sort in descending order. We returned b.joinDate – a.joinDate in the function, it simply reversed the logic that we used in the previous example.
More appropriately we returned -1 if ‘b’ should be placed before ‘a’,1 if ‘b’ should be placed after ‘a’, and 0 if no change. Therefore by this method, we can create a separate function and then use it in the sort() method.
Conclusion
Now we have learned how to sort an object by date property. In this article, we covered various methods such as using the built-in sort() method, the getTime() method, and also a custom sorting function. You can also learn how to sort alphabetically because that is also a common scenario in the real world.