Open In App

Lodash _.sortBy() Method

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:

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.




// 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.




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

Article Tags :