-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

5
  • 1
    So what is not working for you from the answers in the question you linked yourself? Commented Dec 17, 2014 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? Commented Dec 17, 2014 at 17:08
  • 1
    How to sort 2 dimensional array by column value? Commented Dec 17, 2014 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]); Commented Dec 17, 2014 at 17:18
  • possible duplicate of Sort java script array of formatted date Commented Dec 17, 2014 at 17:28

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.