Skip to content

Instantly share code, notes, and snippets.

@Noah-Huppert
Last active December 27, 2015 05:29
Show Gist options
  • Save Noah-Huppert/7274702 to your computer and use it in GitHub Desktop.
Save Noah-Huppert/7274702 to your computer and use it in GitHub Desktop.
Javascript custom sorting problem
//JS Code:
var dates = new Array(//Note if there is a problem with the array definition it would not matter b/c the array gets
//created dynamically in a different order.
"2013-1-1"
"2013-10-10",
"2013-10-15",
"2013-10-22",
"2013-10-22",
"2013-10-28",
"2013-12-17",
"2013-9-10",
"2013-9-15",
"2013-9-15",
"2013-9-17",
"2013-9-20",
"2013-9-23",
"2013-9-4");
dates.sort(function(a, b){
sortA = a.split("-");
sortB = b.split("-");
if(sortA[0] == sortB[0]){//If year is equal to year
if(sortA[1] > sortB[1]){//Month greater than month
return 1;
}
if(sortA[1] < sortB[1]){//Month Less than month
return -1;
}
if(sortA[1] == sortB[1]){//Month equal month
if(sortA[2] > sortB[2]){//Day greater than day
return 1;
}
if(sortA[2] < sortB[2]){//Day less than day
return -1;
}
return 0;
}
return 0;
}
if(sortA[0] > sortB[0]){//Year greater than year
if(sortA[1] > sortB[1]){//Month greater than month
return 1;
}
if(sortA[1] < sortB[1]){//Month Less than month
return -1;
}
if(sortA[1] == sortB[1]){//Month equal month
if(sortA[2] > sortB[2]){//Day greater than day
return 1;
}
if(sortA[2] < sortB[2]){//Day less than day
return -1;
}
return 0;
}
return 1;
}
/*What gets returned:
2013-1-1
2013-10-10
2013-10-15
2013-10-22
2013-10-22
2013-10-28
2013-12-17
2013-9-10
2013-9-15
2013-9-15
2013-9-17
2013-9-20
2013-9-23
2013-9-4*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment