如何在创建 DOM 元素之前按日期排序

How to sort by date before creating DOM elements

我正在循环浏览一些 JSON 并希望显示最新日期的 DOM 元素。我有一个数据日期属性。在将它们创建为 DOM 元素之前,我如何对数组中的每个对象进行排序?

我有以下 --

$.getJSON(ytapiurl, function(data) {
  $.each(data.feed.entry, function(i, item) {
    var pubdate  = item['published']['$t'];
        htmlString +='<div class="cursor col-sm-6 col-md-3 item" data-date="' + fulldate '">Video</div>';

    console.log(new Date(pubdate).getTime());
 });
});

假设 pubdateentry 数组中的 属性 个项目,您可以在创建 html

之前对数组进行排序
$.getJSON(ytapiurl, function (data) {
    data.feed.entry.sort(function (a, b) {
        var fd1 = new Date(a.pubdate);
        var fd2 = new Date(b.pubdate);
        return fd1.getTime() - fd2.getTime();
    })
    $.each(data.feed.entry, function (i, item) {
        var fulldate = new Date(pubdate).toLocaleDateString();
        htmlString += '<div class="cursor col-sm-6 col-md-3 item" data-date="' + fulldate '">Video</div>';
    });
});

技巧是使用日期对象而不是表示日期的字符串对数组进行排序。

var articles = [
   {pubDate: new Date(2000, 0, 1), desc:'one'},
   {pubDate: new Date(1999, 0, 1), desc:'two'},
   {pubDate: new Date(2002, 0, 1), desc:'three'},
   {pubDate: new Date(2001, 0, 1), desc:'four'}
];
console.log(articles);
articles.sort(function(a,b){
    return a.pubDate < b.pubDate; // set desc or asc here
});
articles.forEach(function(article){
   console.log(article.pubDate,article.desc);
   // Write to DOM here
});

Returns

Tue Jan 01 2002 00:00:00 GMT-0600 (Central Standard Time) "three"
Mon Jan 01 2001 00:00:00 GMT-0600 (Central Standard Time) "four"
Sat Jan 01 2000 00:00:00 GMT-0600 (Central Standard Time) "one"
Fri Jan 01 1999 00:00:00 GMT-0600 (Central Standard Time) "two"