nhaa123 nhaa123 - 2 years ago 992
Javascript Question

lodash multi-column sortBy descending

There's a nifty method to sort an array of object based on several propertes:

var data = _.sortBy(array_of_objects, ['type', 'name']);

However that is only for ascending sorting. Is there some handy way of defining direction per column? E.g.

var data = _.sortBy(array_of_objects, [{'type': 'asc'}, {'name': 'desc'}]);

Answer Source

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for odrering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download