Using Javascript with Underscore.js to Sort the other way

Harry picture Harry · Jan 2, 2012 · Viewed 53.3k times · Source

I'm using Javascript sort (with Underscore.js):

_.sortBy(["Bob", "Mary", "Alice"], function (name) {return name})
> ["Alice", "Bob", "Mary"]

I would like the array to return the other way. How do I do that?

["Mary", "Bob", "Alice"]

I don't want to reverse it after it's sorted - I want it to be created the other way around the first time.

Thanks.

Answer

h--n picture h--n · Aug 27, 2012

Instead of throwing underscorejs away, I'd rather use it together with Array.reverse to utilize the best of both.

_.sortBy(["Bob", "Mary", "Alice"], function (name) {return name})
 .reverse()