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!
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With