0

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

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.