如何按日期对对象的嵌套数组进行排序

终极卡夫卡

我正在创建简单的新闻应用程序,并且正在使用Firebase作为后端,我已将新闻文章存储在Cloud firestore中,在我的字段中,我有新闻发布时间,hr:min:sec我想按发布时间(从最新到最早)对接收到的数据进行排序,有什么解决方案吗?提前致谢

var data = [ 
    { news: [ 
          { published_at: "2/22/2021",
           imgUrl: "", 
           id: 159783, 
           title: "short descr", 
           date: "18:11:53", 
           previewText: "some kind of title" } 
           ], 
          newsId: "5GTAbGLfS0hSCOkmTfHD" 
       }, 

       
           
      { news: [ 
          { id: 159783,
           published_at: "2/22/2021", 
           previewText: "some kind of title2",
            title: "short descr", 
            date: "17:19:53", 
            imgUrl: "" 
            } 
         ], 
      newsId: "lw2hzVe0m3dbcmvBj4Vz" } 
  ]

  data.forEach((item)=>{
      var singleItem = item.news
     const finalResult = singleItem.sort((a, b) => b.date - a.date)
     console.log(finalResult)
  })

哈桑·伊玛目(Hassan Imam)

您可以用来string#localeComparehh:mm:ss格式对时间进行排序

const data = [ { news: [ { published_at: "2/22/2021", imgUrl: "", id: 159783, title: "short descr", date: "18:11:53", previewText: "some kind of title" } ], newsId: "5GTAbGLfS0hSCOkmTfHD" }, { news: [ { id: 159783, published_at: "2/22/2021", previewText: "some kind of title2", title: "short descr", date: "17:19:53", imgUrl: "" } ], newsId: "lw2hzVe0m3dbcmvBj4Vz" } ];
data.sort((a,b) => b.news[0].date.localeCompare(a.news[0].date));
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章