Sorting an array by date in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of objects like this −

const arr = [{id: 1, date: 'Mar 12 2012 10:00:00 AM'}, {id: 2, date: 'Mar 8 2012 08:00:00 AM'}];

We are required to write a JavaScript function that takes in one such array and sorts the array according to the date property of each object.

(Either newest first or oldest first).

The approach should be to convert these into JS Date Object and compare their timestamps to sort the array.

Example

The code for this will be −

const arr = [{id: 1, date: 'Mar 12 2012 10:00:00 AM'}, {id: 2, date: 'Mar 8 2012 08:00:00 AM'}];
const sortByDate = arr => {
   const sorter = (a, b) => {
      return new Date(a.date).getTime() - new Date(b.date).getTime();
   }
   arr.sort(sorter);
};
sortByDate(arr);
console.log(arr);

Output

And the output in the console will be −

[
   { id: 2, date: 'Mar 8 2012 08:00:00 AM' },
   { id: 1, date: 'Mar 12 2012 10:00:00 AM' }
]
raja
Published on 20-Nov-2020 10:04:57
Advertisements