How can I sort an array of objects by more then one field using lodash. So for an array like this:
[ {a: 'a', b: 2}, {a: 'a', b: 1}, {a: 'b', b: 5}, {a: 'a', b: 3}, ]
I would expect this result
[ {a: 'a', b: 1}, {a: 'a', b: 2}, {a: 'a', b: 3}, {a: 'b', b: 5}, ]
@tieTYT In edge we do support sorting by multiple properties but at the moment lodash doesn't support parsing property names by . and that's not a priority for the next release. Lodash doesn't do anything extra for arrays returned from callbacks, they're coerced as other values when compared with < or >.
The built-in sort () function works well, but can get cumbersome when sorting arrays of objects. On the other hand, _.sortBy () lets you sort an array of objects by a property name as shown below. The first parameter to sortBy () is the array to sort, and then 2nd parameter is called the iteratees.
Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements. The iteratees are invoked with one argument: (value). collection (Array|Object): The collection to iterate over.
If you want a particular key to sort in descending order, then instead pass in an array in this format: ['property_name', true]. Here are some sample uses of the function followed by an explanation (where homes is an array containing the objects): objSort (homes, 'city') --> sort by city (ascending, case in-sensitive)
This is much easier in a current version of lodash (2.4.1). You can just do this:
var data = [ {a: 'a', b: 2}, {a: 'a', b: 1}, {a: 'b', b: 5}, {a: 'a', b: 3}, ]; data = _.sortBy(data, ["a", "b"]); //key point: Passing in an array of key names _.map(data, function(element) {console.log(element.a + " " + element.b);});
And it will output this to the console:
"a 1" "a 2" "a 3" "b 5"
Warning: See the comments below. This looks like it was briefly called sortByAll
in version 3, but now it's back to sortBy
instead.
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