Javascript

Sort an Array by Date in JavaScript

Sorting an array in Javascript by date can be really tricky sometimes. That’s why we are writing this blog post to show you that, how you can easily sort an array by date in Javascript. So without further due, let’s start

Also Read: How to Check empty objects in Javascript

Sort an Array by Date Value in Javascript

Suppose, we want to sort an array which is like the following array.

const movies = [
    {title: 'The Godfather', rating: 9.2, release: '24 March 1972'},
    {title: 'The Godfather: Part II', rating: 9.0, release: '20 December 1972'},
    {title: 'The Shawshank Redemption', rating: 9.3, release: '14 October 1994'},
];

For sorting this array based on the date value, we can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array. The sort() method returns a new sorted array, but it also sorts the original array in place.

Here is an example of Array sorting based on Date Value

movies.sort(function(a, b) {
    var dateA = new Date(a.release), dateB = new Date(b.release);
    return dateA - dateB;
});

How sorting an array by Date in Javascript work?

In the above-given example, we are returning a positive value, so that the function communicates to sort() that the object b takes precedence in sorting over the object a. If we return a negative value, it will do just the opposite.

So, this is how you sort an array by date in Javascript. Thanks for reading!

Leave a Comment