Open In App

Lodash _.sortBy() Method

Improve
Improve
Like Article
Like
Save
Share
Report

Lodash _.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 iterate. Also, this method performs a stable sort which means it preserves the original sort order of equal elements in an array.

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 }
]


Last Updated : 23 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads