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
arrarray containing three objects. - Calls
_.sortBywitharrandnameas arguments. - Assigns the resulting array to
sortedArr. - Logs
sortedArrto 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 to create a unique array in JavaScript?
- How can I use Lodash in JavaScript?
- How can I use lodash in a JavaScript sandbox?
- How can I remove a value from an array using JavaScript and Lodash?
- How can I use Lodash to find and update an object in a JavaScript array?
- How do lodash and underscore differ in JavaScript?
- How do I use Lodash to zip two JavaScript arrays together?
- How do I use Lodash to merge two arrays in JavaScript?
See more codes...