Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort items in an array by more than one field with lodash

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}, ] 
like image 321
Andreas Köberle Avatar asked Oct 11 '13 08:10

Andreas Köberle


People also ask

Is it possible to sort by multiple properties in Lodash?

@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 >.

How to sort an array of objects by a property name?

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.

How do you sort an array of objects in Python?

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.

How to sort a list in descending order with objects?

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)


1 Answers

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.

like image 197
Daniel Kaplan Avatar answered Oct 11 '22 08:10

Daniel Kaplan