How to use Lodash _.orderBy() Method In Javascript
Lodash _.orderBy() method is similar to the _.sortBy() method except that it allows the sort orders of the iterates to sort by. If orders are unspecified, then all values are sorted in ascending order otherwise order of corresponding values specifies an order of “desc” for descending or “asc” for ascending sort.
Syntax:
_.orderBy(Collection, [ iteratees ], [ orders ]);
Example: In this example, we are sorting the array’s patron in ascending order and age in descending order.
// Requiring the lodash library
const _ = require("lodash");
// Original array
let users = [
{ 'patron': 'jonny', 'age': 48 },
{ 'patron': 'john', 'age': 34 },
{ 'patron': 'john', 'age': 40 },
{ 'patron': 'jonny', 'age': 36 }
];
// Use of _.orderBy() method
// Sort by `patron` in ascending order
// and by `age` in descending order
let sorted_array =
_.orderBy(users, ['patron', 'age'],
['asc', 'desc']);
// Printing the output
console.log(sorted_array);
Output:
[
{ 'patron': 'john', 'age': 40 },
{ 'patron': 'john', 'age': 34 },
{ 'patron': 'jonny', 'age': 48 },
{ 'patron': 'jonny', 'age': 36 }
]
Sort an Object Array by Date in JavaScript
To sort an Object Array by Date in JavaScript, we have different approaches. We are going to learn how to sort an Object Array by Date in JavaScript.
Below are the approaches to sort an Object Array by Date in JavaScript:
Table of Content
- Using sort method with Date objects
- Using sort() method with getTime() method
- Using a custom sorting function
- Using Lodash _.orderBy() Method
- Using Intl.DateTimeFormat and Array.prototype.sort()
Contact Us