Skip to content
Related Articles

Related Articles

Lodash _.sortBy() Method
  • Difficulty Level : Basic
  • Last Updated : 10 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 _.sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee. And also this method performs a stable sort which means it preserves the original sort order of equal elements.

Syntax:

_.sortBy(collection, iteratees)

Parameters: This method accepts two parameters as mentioned above and described below:

  • collection: This parameter holds the collection to iterate over.
  • iteratees: This parameter holds the iteratees to sort by and are invoked with one argument(value).

Return Value: This method is used to return the new sorted array.



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

javascript




// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = [
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 15999 } ];
   
// Use of _.sortBy() method
let gfg = _.sortBy(object, 
    [function(o) { return o.obj; }]);
  
// Printing the output 
console.log(gfg);

Output:

[
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'oppo', 'price': 15999 }
]

Example 2:

javascript




// Requiring the lodash library 
const _ = require("lodash"); 
       
// Original array 
var object = [
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 18999 },
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'oppo', 'price': 15999 } ];
   
// Use of _.sortBy() method
let gfg = _.sortBy(object, ['obj', 'price']);
  
// Printing the output 
console.log(gfg);

Output:

[
  { 'obj': 'moto', 'price': 17999 },
  { 'obj': 'moto', 'price': 19999 },
  { 'obj': 'oppo', 'price': 15999 },
  { 'obj': 'oppo', 'price': 18999 } 
]

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 :