0

I have an array of strings in JS that represent dates on the format M/D/Y where M and D can have one or two digits each. How can I write a callback function do sort this array?

1
  • 3
    Post your existing code please. Commented Nov 24, 2012 at 22:39

2 Answers 2

3

Date.parse() (to which new Date(string) is equivalent) is not consistent across JS implementations, so I should probably manually parse the date strings first for consistency, then do exactly as Minko Gechev suggests:

array.sort(function (d1, d2) {
  function parseDate(str) {
    var parts = str.match(/(\d+)/g);
    // assumes M/D/Y date format
    return new Date(parts[2], parts[0]-1, parts[1]); // months are 0-based
  }
  return parseDate(d1) - parseDate(d2);
});

As an aside, I'd argue you're almost always better off storing Date objects rather than strings, and then formatting your Dates as strings as and when you need them for output anyway, as it makes this sort of manipulation easier, and makes your code clearer too.

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

1 Comment

I agree, but the source dates weren't stored by me.
1

You can also split the strings into their m d y components and compare the components.

array.sort(function(a,b){
  var a1= a.split('/'), b1=b.split('/');
  if(a1[2]==b1[2]){
    return (a1[0]==b1[0])? a1[1]-b1[1]: a1[0]-b1[0];
  }
  return a1[2]-b1[2];
}

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.