I need to sort JSON object based on created date in descending order so that most recently created date data shows first.
var Array = {
"result": {
"items": [
{
"content_sys_id": "10999ec787941d10f2d740c8dabb3503",
"sys_created_on": "2022-08-06 12:08:09"
},
{
"content_sys_id": "730e2e9547b0d110fa462034846d432a",
"sys_created_on": "2022-08-06 12:08:23"
},
{
"content_sys_id": "008f0a2b87dc5d10f2d740c8dabb35a0",
"sys_created_on": "2022-08-02 02:22:20"
},
{
"content_sys_id": "002301478788d15038a740c8dabb350e",
"sys_created_on": "2022-08-07 17:28:42"
},
{
"content_sys_id": "cb895ec787941d10f2d740c8dabb357e",
"sys_created_on": "2022-08-11 23:34:08"
}
],
"count": 5,
"total_records": "5",
"offset": 500,
"has_more": false
}
};
var sortedArray = Array.sort(function(a, b){
var x = a.items.sys_created_on;
var y = b.items.sys_created_on;
return x < y ? -1 : x > y ? 1 : 0;
//return y - x;
//return new Date(b.items.sys_created_on) - new Date(a.items.sys_created_on);
});
console.log("sorted array :: " JSON.stringify(sortedArray)); //getting output as sorted array :: undefined
}
i tried above solutions but no luck so far. Please suggest the solution.
CodePudding user response:
Maybe this works, take in account the fallowing recomendations
- Yo must apply sort method to an array in this case Array.result.items not to Array becouse this is an object
- Before compare dates you need to convert them to a Date type.
I hope it could be helpful
var Array = {
"result": {
"items": [
{
"content_sys_id": "10999ec787941d10f2d740c8dabb3503",
"sys_created_on": "2022-08-06 12:08:09"
},
{
"content_sys_id": "730e2e9547b0d110fa462034846d432a",
"sys_created_on": "2022-08-06 12:08:23"
},
{
"content_sys_id": "008f0a2b87dc5d10f2d740c8dabb35a0",
"sys_created_on": "2022-08-02 02:22:20"
},
{
"content_sys_id": "002301478788d15038a740c8dabb350e",
"sys_created_on": "2022-08-07 17:28:42"
},
{
"content_sys_id": "cb895ec787941d10f2d740c8dabb357e",
"sys_created_on": "2022-08-11 23:34:08"
}
],
"count": 5,
"total_records": "5",
"offset": 500,
"has_more": false
}
};
let sortedItems = Array.result.items.sort((a,b)=>{
let aDate = new Date(a.sys_created_on);
let bDate = new Date(b.sys_created_on);
return bDate - aDate;
});
Array.result.items = sortedItems;
console.log(Array.result.items);
CodePudding user response:
I got my working solution:
var resultSorted = resultUnsorted.items.sort(function(a, b) {
var x = a.sys_created_on;
var y = b.sys_created_on;
return x > y ? -1 : x < y ? 1 : 0;
});