1

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"
}
Jerry Seigle
  • 417
  • 4
  • 12
  • Does this help you ? https://stackoverflow.com/a/10124053/9868549 I literally typed your title in google. – Quentin Grisel Jul 17 '21 at 05:50
  • Does this answer your question? [How to sort an object array by date property?](https://stackoverflow.com/questions/10123953/how-to-sort-an-object-array-by-date-property) – Saurabh Agrawal Jul 17 '21 at 06:05

1 Answers1

2

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)
Gulam Hussain
  • 1,591
  • 10
  • 19