Open In App

Lodash _.orderBy() Method

Last Updated : 18 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
let users = [
    { 'patron': 'jonny', 'age': 48 },
    { 'patron': 'john', 'age': 34 },
    { 'patron': 'john', 'age': 40 },
    { 'patron': 'jonny', 'age': 36 }
];
 
// Use of _.orderBy() method
// Sort by `patron` in ascending order
// and by `age` in descending order
 
let sorted_array =
    _.orderBy(users, ['patron', 'age'],
    ['asc', 'desc']);
 
// Printing the output
console.log(sorted_array);


Output:

[
  { 'patron': 'john',   'age': 40 },
  { 'patron': 'john', 'age': 34 },
  { 'patron': 'jonny',   'age': 48 },
  { 'patron': 'jonny', 'age': 36 }
]

Example 2:

javascript




// Requiring the lodash library
const _ = require("lodash");
 
// Original array
var users = [
    { 'employee': 'hunny', 'salary': 60000 },
    { 'employee': 'munny', 'salary': 40000 },
    { 'employee': 'hunny', 'salary': 55000 },
    { 'employee': 'munny', 'salary': 36000 }
];
 
// Use of _.orderBy() method
// Sort by `employee` in ascending order
// and by `salary` in descending order
 
let sorted_array = _.orderBy(users, ['employee',
    'salary'], ['asc', 'desc']);
 
// Printing the output
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
Previous
Next
Share your thoughts in the comments

Similar Reads