Skip to content

Instantly share code, notes, and snippets.

@natos
Last active February 27, 2016 11:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natos/3402761 to your computer and use it in GitHub Desktop.
Save natos/3402761 to your computer and use it in GitHub Desktop.
Sort array by datetime
// Let's say you have collection of things, like:
var collection = [
{name: '#1 thing', time: '2012-03-16T07:22Z'},
{name: '#2 thing', time: '2012-03-15T12:00Z'},
{name: '#3 thing', time: '2012-03-17T20:25Z'},
{name: '#4 thing', time: '2012-03-13T13:45Z'}
];
// the sorting function
function sortByDateTime(a, b) {
// check this docs page from mozilla
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
// we use date objects to get milliseconds values
return new Date(a.time).valueOf() - new Date(b.time).valueOf();
}
// Apply the sort function
collection.sort(sortByDateTime);
// See te results
console.log(collection);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment