Last active
February 27, 2016 11:01
-
-
Save natos/3402761 to your computer and use it in GitHub Desktop.
Sort array by datetime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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