Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to sort the array of objects by date in ascending and descending order using Javascript?

    • 0
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 15.3k
    Comment on it

    To sort the array of objects by date in ascending and descending order, we are using JavaScript sort() method , as discussed earlier. Below is the code to provide the same functionality.

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click the buttons to sort the array.</p>
    <button onclick="myFunction()">Date asc</button>
    <button onclick="myFunction1()">Date Dsc</button>
    <p id="demo"></p>
    
    <script>
        var record = [
                {id: 1,age :12,subject:"science",date: "9/23/15 13:07"}, 
                {id: 2,age :62,subject:"environment",date: "03/30/15 16:30"}
                ];                                                                                       
    
        for (var i = 0; i < record.length; i++) 
        {
            document.write("<br>");
            document.write(record[i].date);
            document.write(" ");
            document.write(record[i].subject);
        }
    
        function myFunction() 
        {
            record.sort(function(a,b){
            return new Date(a.date).getTime() - new Date(b.date).getTime() 
            });
            for (var i = 0; i < record.length; i++) 
            {
                document.write(record[i].date);
                document.write("<br>");
            }
        }
        function myFunction1() 
        {
            record.sort(function(a,b){
            return new Date(b.date).getTime() - new Date(a.date).getTime() 
            });
            for (var i = 0; i < record.length; i++) 
            {
                document.write(record[i].date);
                document.write("<br>");
            }
        }
    <script>
    </body>
    </html>
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: