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 do lodash and JavaScript differ in terms of usage in software development?
- 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 an online JavaScript compiler with Lodash?
- How can I use Lodash to find the unique key of a JavaScript object?
- How can I use Lodash to manipulate JavaScript objects online?
- How do I use Lodash in JavaScript?
- How can I use lodash in a JavaScript sandbox?
See more codes...