我正在创建简单的新闻应用程序,我使用 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)
})
答案 0 :(得分:2)
您可以使用 string#localeCompare
以 hh: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; }
答案 1 :(得分:0)
我认为你可以这样做
const finalResult = singleItem.sort((a, b) => Date.parse(`${b.published_at} ${b.date}`) - Date.parse(`${a.published_at} ${a.date}`))