javascript-lodashHow can I sort an array of objects by property using Lodash and JavaScript?
To sort an array of objects by property using Lodash and JavaScript, you can use the _.sortBy
function. This function takes an array and a sorting function as arguments and returns a new array sorted according to the sorting function.
For example, to sort an array of objects by their name
property, you can use the following code:
const arr = [
{name: 'John', age: 25},
{name: 'Alice', age: 22},
{name: 'Bob', age: 28},
];
const sortedArr = _.sortBy(arr, 'name');
console.log(sortedArr);
// Output:
// [
// {name: 'Alice', age: 22},
// {name: 'Bob', age: 28},
// {name: 'John', age: 25},
// ]
This code does the following:
- Declares a
arr
array containing three objects. - Calls
_.sortBy
witharr
andname
as arguments. - Assigns the resulting array to
sortedArr
. - Logs
sortedArr
to the console.
Helpful links
More of Javascript Lodash
- How do I use yarn to install and use lodash in a JavaScript project?
- How do I use Lodash in a JavaScript playground?
- How can I use lodash in a JavaScript sandbox?
- How do lodash and underscore differ in JavaScript?
- How do I use Lodash to get unique values in a JavaScript array?
- How can I use Lodash's throttle function in JavaScript?
- How can I check for undefined values in JavaScript using Lodash?
- How do I use Lodash to truncate a string in JavaScript?
- How can I use Lodash to create a unique array in JavaScript?
- How do I use Lodash to zip two JavaScript arrays together?
See more codes...