Reputation: 802
I am trying to sort an array by Year and Month
this is my input:
var MyArray = ["2015-Jun", "2014-Nov", "2015-Dec", "2014-Aug", "2015-May"];
I want this output:
[ "2014-Aug", "2014-Nov", "2015-May", "2015-Jun", "2015-Dec" ]
I found this exemple: http://jsfiddle.net/Tw6xt/63/
It almost works. output:
2014-May,2015-Jun,2015-Dec,2014-Aug,2014-Nov
What am i doing wrong?
Upvotes: 0
Views: 1687
Reputation: 10746
I would change the sort to something like this:
MyArray.sort(function (a,b) {
var as = a.split('-'),
bs = b.split('-');
if(parseInt(as[0])<parseInt(bs[0])){
if(months[as[1]]<months[bs[1]])
return -1;
else if(months[as[1]]>months[bs[1]])
return 1;
else
return 0;
}else if(parseInt(as[0])>parseInt(bs[0])){
return 1;
}
return 0;
});
This will first order by year then order by month, with output: 2014-May,2014-Aug,2014-Nov,2015-Jun,2015-Dec
Upvotes: 1
Reputation: 1699
the setDate() method that you are using sets the day of the month (1 to 31) and will give you some unexpected result since you pass a year "2015" to it.
wrong:
ad.setDate(as[0]);
What you need to do is use the setFullYear() method instead.
ad.setFullYear(as[0]);
HTML
<div>Before sort: <span id="before"></span></div>
<div>After sort: <span id="after"></span></div>
JS
var MyArray = ["2015-Jun", "2014-May", "2015-Dec", "2014-Aug", "2014-Nov"];
document.getElementById("before").innerHTML = String(MyArray);
(function () {
MyArray.sort(function (a,b) {
var ad = new Date(),
bd = new Date(),
months = {
Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5,
Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov:10, Dec:12
};
var as = a.split('-'),
bs = b.split('-');
ad.setFullYear(as[0]);
ad.setMonth(months[as[1]]);
bd.setFullYear(bs[0]);
bd.setMonth(months[bs[1]]);
return ad - bd;
});
})();
document.getElementById("after").innerHTML = String(MyArray);
OUTPUT
Before sort: 2015-Jun,2014-May,2015-Dec,2014-Aug,2014-Nov
After sort: 2014-May,2014-Aug,2014-Nov,2015-Jun,2015-Dec
Upvotes: 2