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
const _ = require( "lodash" );
let object = [
{ 'obj' : 'moto' , 'price' : 19999 },
{ 'obj' : 'oppo' , 'price' : 18999 },
{ 'obj' : 'moto' , 'price' : 17999 },
{ 'obj' : 'oppo' , 'price' : 15999 }];
let sorted_obj = _.sortBy(object,
[ function (o) { return o.obj; }]);
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
const _ = require( "lodash" );
let object = [
{ 'obj' : 'moto' , 'price' : 19999 },
{ 'obj' : 'oppo' , 'price' : 18999 },
{ 'obj' : 'moto' , 'price' : 17999 },
{ 'obj' : 'oppo' , 'price' : 15999 }];
let sorted_array = _.sortBy(object, [ 'obj' , 'price' ]);
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
Please Login to comment...