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 Lodash in a JavaScript playground?
- How can I use Lodash to create a unique array in JavaScript?
- How can I use Lodash's reject function in JavaScript?
- How can I compare the usage of lodash's foreach to the native JavaScript foreach loop?
- How do I use yarn to install and use lodash in a JavaScript project?
- How can I check for undefined values in JavaScript using Lodash?
- How can I use Lodash in JavaScript?
- How can I use Lodash to remove undefined values from an object in JavaScript?
- How can I use Lodash to find and update an object in a JavaScript array?
- How can I use Lodash to union two JavaScript arrays?
See more codes...