Skip to content

JavaScript sort date ascending and descending | Example code

  • by

If your objects have the date information within a String field then convert it into a date to sort dates ascending and descending in JavaScript.

yourArray.sort(function(a, b) { return new Date(a.date) - new Date(b.date) })

or, if they have it within a Date field:

yourArray.sort(function(a, b) { return a.date - b.date })

JavaScript sort date ascending and descending

Simple example code sorting date with time in descending order in JavaScript. The Array.sort method accepts a sort function, which accepts two elements as arguments, and should return:

<!DOCTYPE html>
<html>
<body>

  <script>
    var array = ["25-Jul-2017 12:46:39 pm", 
    "02-Jul-2017 12:52:23 pm", 
    "01-Jul-2021 12:47:18 pm", 
    "25-Jul-2017 12:59:18 pm"];

    array.sort((a, b) => new Date(b).getTime() - new Date(a).getTime())

    console.log(array)

  </script>

</body>
</html> 

Output:

JavaScript sort date ascending and descending

Sort date in ascending order

<script>
    var a = [
    {
      "name": "February",
      "date": "2018-02-04T17:00:00.000Z",
    },
    {
      "name": "March",
      "date": "2018-03-04T17:00:00.000Z",
    },
    {
      "name": "January",
      "date": "2018-01-17T17:00:00.000Z",
    }
    ]

    a.sort(function(a,b){
      return new Date(a.date) - new Date(b.date)
    })

    console.log(a)
</script>

Do comment if you have any doubts or suggestions on this JS sort topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

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