Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort date in Javascript

I have retrieve from ajax query a news feed. In this object, there is a date in this format :

Wed, 22 May 2013 08:00:00 GMT

I would like to sort all objects by date. Is it possible to do this using Javascript ?

UPDATE

Using this piece of code it works fine !

array.sort(function(a,b){
var c = new Date(a.date);
var d = new Date(b.date);
return c-d;
});
like image 806
pxrb66 Avatar asked May 22 '13 10:05

pxrb66


People also ask

How do I sort a date in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.

What is the sort () method?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


2 Answers

1) You can't sort objects. The order of the object's keys is arbitrary.

2) If you want to sort an array by date (and they are already date obects), do the following:

array.sort ( function (date1, date2){
     return date1 - date2
});

If you first need to convert them to date objects, do the following (following the data structure according to your comment below):

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

Example

like image 121
Christoph Avatar answered Sep 19 '22 19:09

Christoph


You may also use a underscore/lodash sortBy

Here's using underscore js to sort date:

 var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'}, 
            {date: '2016-01-13T05:23:38+00:00',other: 'sample'}, 
            {date: '2016-01-15T11:23:38+00:00', other: 'sample'}];

  console.log(_.sortBy(log, 'date'));
  • http://underscorejs.org/#sortBy
  • https://lodash.com/docs#sortBy
like image 35
Woppi Avatar answered Sep 17 '22 19:09

Woppi