Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by date with underscore.js or just plain JS

I have an array of objects that have a 'date' string property. ie:

[
    {
        id: 1,
        startDate: '2011-4-22'
    },
    {
        id: 2,
        startDate: '2012-3-15'
    },
    {
        id: 3,
        startDate: '2011-4-22'
    },
    {
        id: 4,
        startDate: '2012-2-10'
    }
]

I just want to convert the date strings to a date and sort them by startDate DESC. Can someone please tell me how to do this with teh underscore.js _sortBy method or even just plain javascript will do.

Thanks!

like image 778
29er Avatar asked Apr 19 '12 23:04

29er


1 Answers

An Underscore solution could look like this:

a = [ /* ... */ ];

function to_date(o) {
    var parts = o.startDate.split('-');
    o.startDate = new Date(parts[0], parts[1] - 1, parts[2]);
    return o;
}
function desc_start_time(o) {
    return -o.startDate.getTime();
}
var b = _.chain(a)
         .map(to_date)
         .sortBy(desc_start_time)
         .value();

You don't have to use named functions of course but the names do make the logic a bit clearer.

Demo: http://jsfiddle.net/ambiguous/qe9sZ/

In plain JavaScript you could do it like this:

for(var i = 0, parts; i < a.length; ++i) {
    parts = a[i].startDate.split('-');
    a[i].startDate = new Date(parts[0], parts[1] - 1, parts[2]);
}
var b = a.sort(function(a, b) {
    return b.startDate - a.startDate;
});

Demo: http://jsfiddle.net/ambiguous/rPAPG/

like image 50
mu is too short Avatar answered Oct 30 '22 02:10

mu is too short