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 do I get the last element in an array using Lodash in JavaScript?
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash to create a unique array in JavaScript?
- How do I use an online JavaScript compiler with Lodash?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How can I use Lodash to union two JavaScript arrays?
- How do I use Lodash to remove null values from an object in JavaScript?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash's reject function in JavaScript?
- How do I use Lodash with JavaScript?
See more codes...