Sort an array by Date in JavaScript
In this article, we’ll show you how to sort an array by date in JavaScript. When you are working with an array of objects that contains a date field and we want to sort an array based on the date values then we can use the sort()
method of an array.
There are many ways to do sorting in JavaScript but in this article, we will go with the default function sort()
of an array. Later, we will show you the sorting by moment js library.
Sample Array:
Let’s take an example to sort an array therefore we will use the following sample array which contains a date object.
1 2 3 4 5 6 7 | const students = [ { name: 'Liam', joinDate: new Date('2019-06-28') }, { name: 'Noah', joinDate: new Date('2019-06-10') }, { name: 'William', joinDate: new Date('2019-06-12') }, { name: 'James', joinDate: new Date('2019-06-08') }, { name: 'Lucas', joinDate: new Date('2019-06-21') } ] |
Sort an array by date descending
First, we will sort the above sample array in descending order by joinDate
attribute. Use the following code for descending sorting.
1 | const sortedStudents = students.sort((a, b) => b.joinDate > a.joinDate ? 1: -1); |
Sort an array by date ascending
In the second example, we will sort the sample array in ascending order by joinDate
attribute and for that use the following code.
1 | const sortedStudents = students.sort((a, b) => b.joinDate < a.joinDate ? 1: -1); |
Use slice() method with sort()
When we use the sort()
method then it will return a sorted array but it also sorts an existing array, thus both students
and sortedStudents
variables become the same.
To prevent the sorting of an existing array, we will use the slice()
method. Check out the below code to sort an array by date descending.
1 | const sortedStudents = students.slice().sort((a, b) => b.joinDate > a.joinDate ? 1: -1); |
That’s it for today.
Thank you for reading. Happy Coding..!!
I’m not sure where you’re getting your info, but great topic. I needs to spend some time learning much more or understanding more.
Thanks for great info I was looking for this information for my mission.