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 variablearrwhich stores an array of objects._.orderBy(): uses Lodash'sorderByfunction to order thearrarray of objects by theageproperty in ascending order.console.log(): prints the ordered array of objects to the console.
Helpful links
More of Javascript Lodash
- How do I use Lodash to zip two JavaScript arrays together?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash to check if an object is empty in Javascript?
- How do I use Lodash templates with JavaScript?
- How do I use Lodash to compare two arrays in JavaScript?
- How can I use Lodash to manipulate JavaScript objects online?
- How do I use Lodash in a JavaScript playground?
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
See more codes...