What is lodash.orderby?
The lodash.orderby package is a utility library that provides a method for sorting collections (arrays or objects) based on multiple criteria. It is part of the larger Lodash library, which is known for its performance and ease of use.
What are lodash.orderby's main functionalities?
Sort by Single Property
This feature allows you to sort an array of objects by a single property. In this example, the users array is sorted by the 'user' property in ascending order.
const _ = require('lodash.orderby');
const users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 34 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 36 }
];
const sortedUsers = _.orderBy(users, ['user'], ['asc']);
console.log(sortedUsers);
Sort by Multiple Properties
This feature allows you to sort an array of objects by multiple properties. In this example, the users array is first sorted by the 'user' property in ascending order, and then by the 'age' property in descending order.
const _ = require('lodash.orderby');
const users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 34 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 36 }
];
const sortedUsers = _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
console.log(sortedUsers);
Sort by Nested Properties
This feature allows you to sort an array of objects by nested properties. In this example, the users array is sorted by the 'details.age' property in ascending order.
const _ = require('lodash.orderby');
const users = [
{ 'user': 'fred', 'details': { 'age': 48 } },
{ 'user': 'barney', 'details': { 'age': 34 } },
{ 'user': 'fred', 'details': { 'age': 40 } },
{ 'user': 'barney', 'details': { 'age': 36 } }
];
const sortedUsers = _.orderBy(users, ['details.age'], ['asc']);
console.log(sortedUsers);
Other packages similar to lodash.orderby
sort-array
The sort-array package provides a simple and flexible way to sort arrays of objects by multiple properties. It is similar to lodash.orderby but is a smaller, more focused library specifically for sorting arrays.
array-sort
The array-sort package allows you to sort arrays of objects by multiple properties. It is similar to lodash.orderby but offers a more concise syntax and is focused solely on sorting functionality.
sort-by
The sort-by package provides a utility for sorting arrays of objects by multiple properties. It is similar to lodash.orderby but is a smaller, more lightweight library with a focus on simplicity and ease of use.
lodash.orderby v4.6.0
The lodash method _.orderBy
exported as a Node.js module.
Installation
Using npm:
$ {sudo -H} npm i -g npm
$ npm i --save lodash.orderby
In Node.js:
var orderBy = require('lodash.orderby');
See the documentation or package source for more details.