Friday 28 December 2018

How to sort array by date In JavaScript?




I have a problem to sort arrays that are in an array object by date.



I have an array object as below.




[
{
"name": "February",
"plantingDate": "2018-02-04T17:00:00.000Z",
},
{
"name": "March",
"plantingDate": "2018-03-04T17:00:00.000Z",
},

{
"name": "January",
"plantingDate": "2018-01-17T17:00:00.000Z",
}
]


How to sort the array in the array object from January to December, as below.



[

{
"name": "January",
"plantingDate": "2018-01-17T17:00:00.000Z",
},
{
"name": "February",
"plantingDate": "2018-02-04T17:00:00.000Z",
},
{
"name": "March",

"plantingDate": "2018-03-04T17:00:00.000Z",
}
]


I beg for help.



Thank you in advance.


Answer



Parse strings to get Date objects, then sort by compare function.






var a = [
{
"name": "February",
"plantingDate": "2018-02-04T17:00:00.000Z",
},
{
"name": "March",

"plantingDate": "2018-03-04T17:00:00.000Z",
},
{
"name": "January",
"plantingDate": "2018-01-17T17:00:00.000Z",
}
]

a.sort(function(a,b){
return new Date(a.plantingDate) - new Date(b.plantingDate)

})

console.log(a)





As Barmar commented,



a.sort(function(a,b){

return a.plantingDate > b.plantingDate;
})


will also gonna work.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...