I am trying to sort this JavaScript object array based on the Planned Start
[{"EPRID":"123","AssetName":"AS1","Identifier":"","ID":"C399","Category":"blank","This_ID":"0023-E","Approval status":"Need More Information","Status":"initial","Phase":"Implementation","Planned Start Date":"10/31/2017","Planned End Date":"22/11/2017","Description":"as1 testing","Requestor":"bob","Comments":"test comment","Comment_Updated_By":"jim","Comment_Updated_Timestamp":"09/14/2017 08:00:55"},
{"EPRID":"321","AssetName":"AS3","Identifier":"C19","ID":null,"Category":"Normal Changes","This_ID":"0013-E","Approval status":null,"Status":"initial","Phase":"Implementation","Planned Start Date":"11/21/2016","Planned End Date":"12/12/2016","Description":"as3 testing","Requestor":"joe","Comments":null,"Comment_Updated_By":null,"Comment_Updated_Timestamp":null},
{"EPRID":"213","AssetName":"AS5","Identifier":"C113","ID":null,"Category":"Normal Changes","This_ID":"0143-E","Approval status":null,"Status":"initial","Phase":"Authorization","Planned Start Date":"11/05/2017","Planned End Date":"11/05/2017","Description":"as5 testing","Requestor":"john","Comments":null,"Comment_Updated_By":null,"Comment_Updated_Timestamp":null}]
I have tried the following:
rowObj.sort(function(a, b) {
return a["Planned Start Date"] < b["Planned Start Date"];
});
Which I found from 979256
I have also tried the localeCompare()
but still can seem to get my desired result.
Try this:
rowObj.sort(function (a, b) {
let aStartDate=new Date(a["Planned Start Date"]);
let bStartDate=new Date(b["Planned Start Date"]);
if (aStartDate.getTime() > bStartDate.getTime()) {
return 1;
}
if (aStartDate.getTime() < bStartDate.getTime()) {
return -1;
}
return 0;
});
console.log(rowObj);
The sort in javascript is a string sort. But you want to compare dates. So convert the string to date and then compare
rowObj.sort(function(a, b) {
return new Date(a["Planned Start Date"]) < new Date(b["Planned Start Date"]);
});
You need to convert the compare values to date and return a value of either 0, 1, or -1.
arr.sort(function(a,b){
return new Date(a['Planned Start Date']) - new Date(b['Planned Start Date']);
});
or reversed:
arr.sort(function(a,b){
return new Date(b['Planned Start Date']) - new Date(a['Planned Start Date']);
});
See this post for more details: Sort Javascript Object Array By Date
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.