1

what would be the best way to sort an array of date strings as such :

var array = ["Tue 7/28", "Sat 8/1", "Sun 8/2", "Mon 7/27", "Thu 7/30", "Fri 7/31", "Wed 7/29"];

into this:

var array = ["Mon 7/27", "Tue 7/28", "Wed 7/29", "Thu 7/30", "Fri 7/31", "Sat 8/1", "Sun 8/2"];

1 Answer 1

3

You need to make the dates comparable somehow, so you can use a function to convert them into something comparable. You can skip the weekday and get the month and day and turn that into a number:

function decodeDate(s) {
  parts = s.substr(4).split('/');
  return parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10);
}

Using that you can sort the array:

array.sort(function(a, b){ return decodeDate(a) - decodeDate(b); });

Demo:

function decodeDate(s) {
  parts = s.substr(4).split('/');
  return parseInt(parts[0], 10) * 40 + parseInt(parts[1], 10);
}

var array = ["Tue 7/28", "Sat 8/1", "Sun 8/2", "Mon 7/27", "Thu 7/30", "Fri 7/31", "Wed 7/29"];

array.sort(function(a, b){ return decodeDate(a) - decodeDate(b); });

document.write(JSON.stringify(array));

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

1 Comment

@JohnDoe: I'm not an alot. ;) google.se/…

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.