javascript-lodashHow do I use Lodash to sort an array of objects by a specific property in JavaScript?
To use Lodash to sort an array of objects by a specific property in JavaScript, you can use the _.sortBy()
function. This function will take an array of objects and a property name as arguments and will return a new array sorted by the specified property.
For example:
const array = [
{ name: 'John', age: 30 },
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 25 }
];
const sortedArray = _.sortBy(array, 'age');
console.log(sortedArray);
Output example
[
{ name: 'Alice', age: 20 },
{ name: 'Bob', age: 25 },
{ name: 'John', age: 30 }
]
const array
: declaring a constant variable and assigning it to an array of objects.const sortedArray
: declaring a constant variable and assigning it to the result of calling_.sortBy()
with thearray
variable and the property name'age'
as arguments._.sortBy()
: Lodash function used to sort an array of objects by a specific property.
Helpful links
More of Javascript Lodash
- How do I use Lodash to zip two JavaScript arrays together?
- How can I use Lodash's xor function to manipulate JavaScript objects?
- How do I use Lodash in a JavaScript playground?
- How can I use Lodash to remove undefined values from an object in JavaScript?
- How can I use Lodash's uniq() function to remove duplicate values from a JavaScript array?
- How can I use Lodash to compare two arrays in JavaScript?
- How do I use yarn to install and use lodash in a JavaScript project?
- 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 lodash and underscore differ in JavaScript?
See more codes...