简体   繁体   English

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

[英]How to sort nested array of objects by date

I am creating simple News application, And i am using Firebase as back-end, I have stored News articles in Cloud firestore, In my fields i have News publication time hr:min:sec I want to sort received data by publication time, from the latest to the oldest, any solutions?我正在创建简单的新闻应用程序,并且我使用 Firebase 作为后端,我已将新闻文章存储在 Cloud firestore 中,在我的字段中我有新闻发布时间hr:min:sec我想按发布时间对收到的数据进行排序,从从最新到最旧,有什么解决方案吗? Thanks in advance提前致谢

 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) })

You can use string#localeCompare to sort time in hh:mm:ss format.您可以使用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; }

I think you can do something like this我认为你可以做这样的事情

const finalResult = singleItem.sort((a, b) => Date.parse(`${b.published_at} ${b.date}`) - Date.parse(`${a.published_at} ${a.date}`))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM