Reputation: 3260
So I'm attempt to take an array like
["2015/10","2015/1","2015/6","2015/12","2015/3","2015/7","2015/2","2016/1","2015/8","2015/5","2015/11","2015/9","2015/4"]
, where the XXXX/YY
is year/month format, and sort it from least to greatest.
Attempt, using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort as a reference:
month_keys.sort(function(x,y){
var partsX = x.split('/'), partsY = y.split('/');
return partsX[0] < partsY[0] ? -1 : ( partsX[1] < partsY[1] ? -1 : 1 );
})...
and that gives me
["2015/1","2015/11","2016/1","2015/10","2015/12","2015/2","2015/3","2015/5","2015/5","2015/6","2015/7","2015/8","2015/9"]
in the example array I gave at the beginning. What am I doing wrong?
Upvotes: 1
Views: 59
Reputation: 2562
You have strings representing numbers. Just put a '+' before the variable to convert it to number:
return +partsX[0] < +partsY[0] ? -1 : ( +partsX[1] < +partsY[1] ? -1 : 1 );
I works...
Upvotes: -1
Reputation: 318468
You are comparing strings, not numbers. When comparing strings, they are compared char by char so anything starting with an 1 comes before something starting e.g. with a 2. Even if it's 10 vs 2.
Convert them to numbers and you should get the order you want:
var partsX = +x.split('/'),
partsY = +y.split('/');
You also need to fix the actual comparison:
if (partsX[0] < partsY[0]) return -1;
else if (partsX[0] > partsY[0]) return 1;
else if (partsX[1] < partsY[1]) return -1;
else if (partsX[1] > partsY[1]) return 1;
else return 0;
Upvotes: 5