• Post category:JavaScript
  • Reading time:4 mins read

In this article, we’ll show you how to sort an object 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.

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.

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.

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.

const sortedStudents = students.slice().sort((a, b) => b.joinDate > a.joinDate ? 1: -1);

I hope you find this article helpful.
Thank you for reading. Happy Coding..!!

Leave a Reply