Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Ascending vs Descending sort order with Async.js sortBy

Ascending vs Descending sort order with Async.js sortBy

Problem

I'm trying to Sort an array of objects by their date property using Async.sortBy, from most recent to oldest. A bit of googleing suggests that I reverse sort order by passing obj.date * -1 in the callback instead of obj.date, but this does not have the intended effect. Obviously because the result of that is just NaN.

My dates are in the form 2012-07-12 using today's date as an example.

Sorry fr the brevity and lack of code samples, I'm on the road on my iPad at the moment.

I could just reverse the output array of the sorting I guess but that's not a particularly nice Solution.

[{title: "title", date: "2012-07-12"}, {title: "title2", date: "2011-07-12"}]
Problem courtesy of: Austin Yun

Solution

what about this solution?

async.sortBy([{title: "title", date: "2012-07-12"}, {title: "title2", date: "2011-07-12"}], function(myObject, callback){
    return parseInt( myObject.date.split( '-' ).join(''), 10 ) * -1;
}, function(err, results){ ... });

in converts the date string into a sortable integer and reverses it by multipling with -1.

Solution courtesy of: zaphod1984

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Ascending vs Descending sort order with Async.js sortBy

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×