Currently I have an array like this
var arr = [ ["A", "04/02/2014"], ["B", "06/06/2014"], etc]
WHat I want to do is to sort it by date, which is in format MMDDYYYY, swapping the rows where needed.
Currently I have an array like this
var arr = [ ["A", "04/02/2014"], ["B", "06/06/2014"], etc]
WHat I want to do is to sort it by date, which is in format MMDDYYYY, swapping the rows where needed.
This requires a custom sort function.
function compare( a, b ) {
var aDate = new Date( a[1] );
var bDate = new Date( b[1] );
if( aDate < bDate )
return -1;
if( aDate > bDate )
return 1;
return 0;
}
What this compare function does is it converts the string date in array index 1 into an actual date which can be sorted properly. Then it compares the two dates together to order them. This will sort with earliest at the beginning. If you want to sort with latest at the beginning, you would swap the return values so that the first return value is 1, and the second return value is -1.
This is a sample usage of ordering by date:
var arr = [ ["A", "04/02/2014"], ["C", "06/06/2015"], ["B", "06/06/2014"] ];
arr.sort(compare);
And you get:
[["A", "04/02/2014"], ["B", "06/06/2014"], ["C", "06/06/2015"]]
For more information on custom sorting, check out these SO posts: Sort array of objects by string property value in JavaScript or Sort an array with arrays in it by string