I have an array of objects containing integer representations of years/months:
[
{
year : 2014,
month : 10
},
{
year : 2011,
month : 6
},
{
year : 2014,
month : 11
}
]
I need to sort them by month and year so that the most recent object is first.
Currently I am performing two sorts in order to achieve this:
items.sort(function(a, b){
if (a.month === b.month) {
return 0;
} else if (b.month > a.month) {
return 1;
}
return -1;
});
items.sort(function(a, b){
if (a.year === b.year) {
return 0;
} else if (b.year > a.year) {
return 1;
}
return -1;
});
First I am sorting by the month, then I am sorting by the year.
Although this works fine, it seems a bit hacky. How can I sort this array correctly using a single sort function?
Thanks in advance.