How to use Lodash _.orderBy() Method In Javascript
In this approach, we will use the Lodash _.orderBy() method. 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: The below example uses the Lodash _.orderBy() method to sort an array of objects based on a key in JavaScript.
const _ = require('lodash');
let arr = [
{ name: 'Arrays', topic: 'Data Structures' },
{ name: 'Recursion', topic: 'Algorithms' },
{ name: 'JavaScript', topic: 'Programming' }
];
arr = _.orderBy(arr, ['name'], ['asc']);
console.log(arr);
Output:
[
{ name: 'Arrays', topic: 'Data Structures' },
{ name: 'JavaScript', topic: 'Programming' },
{ name: 'Recursion', topic: 'Algorithms' }
]
How to Sort an Array of Objects Based on a Key in JavaScript ?
In JavaScript, sorting an array of objects based on the key consists of iterating over the array, applying the sort() method or other approaches, and arranging the array in the desired sorting order.
Table of Content
- Using sort() method
- Using Custom Sorting Function
- Using Lodash _.orderBy() Method
- Using Intl.Collator