-1

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.

Sort java script array of formatted date

Johnti
  • 133
  • 2
  • 2
  • 8
  • 1
    So what is not working for you from the answers in the question you linked yourself? – krillgar Dec 17 '14 at 17:08
  • 1
    Do you have a question? Is there some code you've tried that isn't cutting it? Have you tried to modify the (very on-target) linked question? – Paul Roub Dec 17 '14 at 17:08
  • 1
    [How to sort 2 dimensional array by column value?](http://stackoverflow.com/questions/16096872/how-to-sort-2-dimensional-array-by-column-value) – epascarello Dec 17 '14 at 17:11
  • You should be able to use the answer you referenced. Since you know `a` and `b` are arrays themselves just use the correct index when grabbing the date. ex.`var da = new Date(a[1]);` – kendotwill Dec 17 '14 at 17:18
  • possible duplicate of [Sort java script array of formatted date](http://stackoverflow.com/questions/26975803/sort-java-script-array-of-formatted-date) – Kivak Wolf Dec 17 '14 at 17:28

1 Answers1

1

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

Community
  • 1
  • 1
Kivak Wolf
  • 830
  • 8
  • 29