Lodash _.sortBy() Method

Last Updated : 9 Jan, 2025

The _.sortBy() method in Lodash arranges items from smallest to largest or from A to Z, depending on what they are. It also keeps things in the same order if they're the same, like if you have two of the same numbers or words.

Syntax:

_.sortBy(collection, [iteratees]);

Parameters:

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

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

Example 1: In this example, we are sorting the object array using the _.sortBy() method. we have only used 'obj' for sorting the array in ascending order.

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let object = [
    { 'obj': 'moto', 'price': 19999 },
    { 'obj': 'oppo', 'price': 18999 },
    { 'obj': 'moto', 'price': 17999 },
    { 'obj': 'oppo', 'price': 15999 }];

// Use of _.sortBy() method
let sorted_obj = _.sortBy(object,
    [function (o) { return o.obj; }]);

// Printing the output 
console.log(sorted_obj);

Output:

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

Example 2: In this example, we are sorting the object array using the _.sortBy() method. we have used 'obj' and 'price' for sorting the array in ascending order. so if value of 'obj' are same then it will check for the 'price' in ascending order.

javascript
// Requiring the lodash library 
const _ = require("lodash");

// Original array 
let object = [
    { 'obj': 'moto', 'price': 19999 },
    { 'obj': 'oppo', 'price': 18999 },
    { 'obj': 'moto', 'price': 17999 },
    { 'obj': 'oppo', 'price': 15999 }];

// Use of _.sortBy() method
let sorted_array = _.sortBy(object, ['obj', 'price']);

// Printing the output 
console.log(sorted_array);

Output:

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