3

I am trying to sort results from a prop by date & time. Not sure how to do this.

props.data.map((r) => {
      console.log(r);
    });

array example

{
    "date": "2021-07-17",
    "time": "3:00",
    "title": "First Title",
    "description": "Testing"
}, {
    "date": "2021-07-17",
    "time": "3:00",
    "title": "Second Title",
    "description": "Testing"
}
2

1 Answer 1

4

Convert date into timestamp then compare timestamp to sort them using sort array method.

More about sort method on MDN

const data = [
{
    "date": "2021-07-17",
    "time": "3:00",
    "title": "First Title",
    "description": "Testing"
}, {
    "date": "2021-07-18",
    "time": "3:00",
    "title": "Second Title",
    "description": "Testing"
},
{
    "date": "2021-07-18",
    "time": "2:59",
    "title": "Second Title",
    "description": "Testing"
 }
]

const sorted = data.sort((a,b)=>{
  const dateA = new Date(`${a.date} ${a.time}`).valueOf();
  const dateB = new Date(`${b.date} ${b.time}`).valueOf();
  if(dateA > dateB){
    return 1; // return -1 here for DESC order
  }
  return -1 // return 1 here for DESC Order
});
console.log(sorted)

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

6 Comments

Works perfect. Is there a way to do this with "time"
it works for combination of both date and time properties. do you mean sort only by time value?
Yes sort only by time
what if time is same but date is different?
Ok then you can use the above code. it will work fine.
|

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.