Lodash _.orderBy() Method
Last Updated :
18 Oct, 2023
Lodash _.orderBy() method is similar to the _.sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort.
Syntax:
_.orderBy(Collection, [ iteratees ], [ orders ]);
Parameters:
- Collection: This parameter holds the name of the collection that needs to be sorted
- iteratees: This parameter holds the value that needs to be sorted.
- order: This parameter holds the sort orders of iterates it can be “asc” for ascending or can be “desc” for descending.
Return Value:
This method returns the new sorted array.
Example 1: In this example, we are sorting the array’s patron in ascending order and age in descending order.
javascript
const _ = require( "lodash" );
let users = [
{ 'patron' : 'jonny' , 'age' : 48 },
{ 'patron' : 'john' , 'age' : 34 },
{ 'patron' : 'john' , 'age' : 40 },
{ 'patron' : 'jonny' , 'age' : 36 }
];
let sorted_array =
_.orderBy(users, [ 'patron' , 'age' ],
[ 'asc' , 'desc' ]);
console.log(sorted_array);
|
Output:
[
{ 'patron': 'john', 'age': 40 },
{ 'patron': 'john', 'age': 34 },
{ 'patron': 'jonny', 'age': 48 },
{ 'patron': 'jonny', 'age': 36 }
]
Example 2:
javascript
const _ = require( "lodash" );
var users = [
{ 'employee' : 'hunny' , 'salary' : 60000 },
{ 'employee' : 'munny' , 'salary' : 40000 },
{ 'employee' : 'hunny' , 'salary' : 55000 },
{ 'employee' : 'munny' , 'salary' : 36000 }
];
let sorted_array = _.orderBy(users, [ 'employee' ,
'salary' ], [ 'asc' , 'desc' ]);
console.log(sorted_array);
|
Output:
[
{ 'employee': 'hunny', 'salary': 60000 },
{ 'employee': 'hunny', 'salary': 55000 },
{ 'employee': 'munny', 'salary': 40000 },
{ 'employee': 'munny', 'salary': 36000 }
]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...