I am working on one small application
in that i want to sort the array of objets by two values
one is time stamp and one in string
I tried this below snippet but its not satisfying the below condition
I want this object mentioned in snippet should sorted based on the object should contain sport as cricket
first and empty value as second and both are sorted by date ascending order
var content = [
{
"first_name": "musk",
"sport": "cricket",
"created_date": "2022-08-12 04:03:08",
},
{
"first_name": "john",
"sport": "",
"created_date": "2022-08-01 23:00:46",
},
{
"first_name": "robot",
"sport": "cricket",
"created_date": "2022-08-10 23:00:46",
},
{
"first_name": "roy",
"sport": "",
"created_date": "2022-07-31 23:00:46",
},
]
content.sort(function compare( a, b ) {
if ( a.sport < b.sport || (new Date(a.created_date) < new Date(b.created_date))){
return 1;
}
if ( a.sport > b.sport || (new Date(a.created_date) < new Date(b.created_date)) ){
return -1;
}
return 0;
});
console.log(content)
Attached the expected result
expected result
var content = [
{
"first_name": "robot",
"sport": "cricket",
"created_date": "2022-08-10 23:00:46",
},
{
"first_name": "musk",
"sport": "cricket",
"created_date": "2022-08-12 04:03:08",
},
{
"first_name": "roy",
"sport": "",
"created_date": "2022-07-31 23:00:46",
},
{
"first_name": "john",
"sport": "",
"created_date": "2022-08-01 23:00:46",
},
]
can anyone help me with what i am doing wrong in snippet