Skip to content
Related Articles

Related Articles

Lodash _.orderBy() Method
  • Last Updated : 06 Sep, 2020
GeeksforGeeks - Summer Carnival Banner

Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, collection, strings, objects, numbers, etc. The _.orderBy() method is similar to _.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: This method accepts three parameters as mentioned above and described below:

  • collection: This parameter holds the collection to iterate over.
  • iteratee: This parameter holds the iteratees to sort by.
  • order: This parameter holds the sort orders of iteratees.

Return Value: This method returns the new sorted array.

Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.






// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var 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 gfg = _.orderBy(users, ['patron', 'age'], 
             ['asc', 'desc']);
  
// Printing the output 
console.log(gfg);

Output:

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

Example 2:




// 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 gfg = _.orderBy(users, ['employee'
           'salary'], ['asc', 'desc']);
  
// Printing the output 
console.log(gfg);

Output:

[
  { 'employee': 'hunny',   'salary': 60000 },
  { 'employee': 'hunny', 'salary': 55000 },
  { 'employee': 'munny',   'salary': 40000 },
  { 'employee': 'munny', 'salary': 36000 }
]

Note: This code will not work in normal JavaScript because it requires the library lodash to be installed.

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :