简体   繁体   中英

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? 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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