Sort an Object Array by Date in JavaScript

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 zambiatek_outer() {
    Arr.sort(function (a, b) {
        return new Date(a.date) - new Date(b.date);
    });
 
    console.log(JSON.stringify(Arr));
}
 
zambiatek_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 zambiatek_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;
};
 
zambiatek_outer();


Output

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

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button