Open In App
Related Articles

Sort an Object Array by Date in JavaScript

Improve Article
Improve
Save Article
Save
Like Article
Like

In this article, we will see the methods to sort an array of an object by date, there is a number of methods but we’re going to see a few of the most preferred methods. 

Javascript Date Object: The Date object in JavaScript is used to represent a moment in time. This time value is since 1 January 1970 UTC (Coordinated Universal Time). We can create a date using the Date object by calling the new Date() constructor as shown in the below syntax. 

Syntax:

new Date();
new Date(value);
new Date(dateString);
new Date(year, month, day, hours, minutes, seconds, milliseconds);

Example 1: This example sorts the array of objects by date by using the Date object. 

Javascript




let Arr = [
    { id: "1", date: "Mar 11 2012 10:00:00 AM" },
    { id: "2", date: "Mar 8 2012 08:00:00 AM" }
];
 
function geeks_outer() {
    Arr.sort(function (a, b) {
        return new Date(a.date) - new Date(b.date);
    });
 
    console.log(JSON.stringify(Arr));
}
 
geeks_outer();


Output

[{"id":"2","date":"Mar 8 2012 08:00:00 AM"},{"id":"1","date":"Mar 11 2012 10:00:00 AM"}]

Example 2: This example is the same as the previous one but with a little modification in the sort function. 

Javascript




let Arr = [
    { id: "1", date: "Mar 12 2012 10:00:00 AM" },
    { id: "2", date: "Mar 8 2012 08:00:00 AM" }
];
 
function geeks_outer() {
    Arr.sort(GFG_sortFunction);
    console.log(JSON.stringify(Arr));
}
 
function GFG_sortFunction(a, b) {
    let dateA = new Date(a.date).getTime();
    let dateB = new Date(b.date).getTime();
    return dateA > dateB ? 1 : -1;
};
 
geeks_outer();


Output

[{"id":"2","date":"Mar 8 2012 08:00:00 AM"},{"id":"1","date":"Mar 12 2012 10:00:00 AM"}]

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Jun, 2023
Like Article
Save Article
Previous
Next
Similar Reads
Complete Tutorials