Skip to content

Sort array by date JavaScript | Example code

  • by

To sort an array by date first convert given strings into dates, and then subtract them to get a value that is either negative, positive, or zero.

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

Sort array by date JavaScript

Simple example code parse strings to get Date objects, then sort by compare function.

<!DOCTYPE html>
<html>
<body>

  <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>

</body>
</html> 

Output:

Sort array by date JavaScript

Using the arrow function way

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

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

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

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.