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.
To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
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.localeCompare(b.plantingDate);
})
will also work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With