Skip to content
Related Articles
Open in App
Not now

Related Articles

Sort an Object Array by Date in JavaScript

Improve Article
Save Article
  • Last Updated : 20 Dec, 2022
Improve Article
Save Article

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. 

html




<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <h3>
        JavaScript | Sort Object Array By Date
    </h3>
 
    <button onclick="geeks_outer()">
        Click To Sort
    </button>
 
    <p id="GFG_P" style="color:green;"></p>
 
    <script>
        var array = [{id: "1", date: "Mar 11 2012 10:00:00 AM"},
                    {id: "2", date: "Mar 8 2012 08:00:00 AM"}];
         
        var el = document.getElementById("GFG_P");
        function geeks_outer() {
            array.sort(function(a, b){
             
                return new Date(a.date) - new Date(b.date);
            });
         
            el.innerHTML = JSON.stringify(array);
        }
         
    </script>
</body>

Output:

 

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

html




<body style="text-align:center;">
 
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <h3>
        JavaScript | Sort Object Array By Date.
    </h3>
 
    <button onclick="geeks_outer()">
        Click To Sort
    </button>
 
    <p id="GFG_P" style="color:green;"></p>
 
    <!-- Script to sort array of object by date -->
    <script>
        var array = [{id: "1", date: "Mar 12 2012 10:00:00 AM"},
                    {id: "2", date: "Mar 8 2012 08:00:00 AM"}];
         
        var el = document.getElementById("GFG_P");
                 
        function geeks_outer() {
            array.sort(GFG_sortFunction);
            el.innerHTML = JSON.stringify(array);
        }
         
        function GFG_sortFunction(a, b) {
            var dateA = new Date(a.date).getTime();
            var dateB = new Date(b.date).getTime();
            return dateA > dateB ? 1 : -1;
        };
    </script>
</body>

Output:

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!