VOOZH about

URL: https://www.geeksforgeeks.org/javascript/lodash-_-sortby-method/

⇱ Lodash _.sortBy() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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.

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.

Output:

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