Sort date in Javascript

前端 未结 3 1578

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-15 01:47

    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

提交回复
热议问题