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"
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With