javascript-lodashHow can I use Lodash to order an array of objects by a specific property in JavaScript?
Using Lodash, you can easily order an array of objects by a specific property in JavaScript. The following example code demonstrates how to do this:
// array of objects
const arr = [
{name: 'John', age: 20},
{name: 'Tom', age: 18},
{name: 'Bob', age: 19}
];
// order array of objects by the age property
const orderedArr = _.orderBy(arr, ['age'], ['asc']);
console.log(orderedArr);
Output example
[
{name: 'Tom', age: 18},
{name: 'Bob', age: 19},
{name: 'John', age: 20}
]
Code explanation
const arr
: creates a constant variablearr
which stores an array of objects._.orderBy()
: uses Lodash'sorderBy
function to order thearr
array of objects by theage
property in ascending order.console.log()
: prints the ordered array of objects to the console.
Helpful links
More of Javascript Lodash
- How can I use Lodash to create a unique array in JavaScript?
- How do I use Lodash to zip two JavaScript arrays together?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash's throttle function in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How can I check for undefined values in JavaScript using Lodash?
- How do I use Lodash to get unique values in a JavaScript array?
- How can I use Lodash to capitalize a string in JavaScript?
See more codes...