Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
68
rated 0 times [  70] [ 2]  / answers: 1 / hits: 197369  / 10 Years ago, tue, april 8, 2014, 12:00:00

There's a nifty method to sort an array of objects based on several properties:



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'}]);

More From » sorting

 Answers
30

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 ordering (asc, desc):



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


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



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

[#71566] Sunday, April 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
clifford

Total Points: 86
Total Questions: 114
Total Answers: 111

Location: Wales
Member since Mon, May 17, 2021
3 Years ago
;