Friday, December 28, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...