How to use external libraries like Lodash In Javascript
To sort an array of objects using Lodash, first ensure Lodash is imported. Then, utilize _.sortBy(array, ‘property’) to sort the array by the specified property, such as age or name. This method returns a new sorted array.
Example: In this example we sorts an array of objects by the age property using Lodash’s _.sortBy method. After sorting, the array elements will be ordered by age in ascending order.
let array = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 20 }
];
array = _.sortBy(array, 'age');
Output:
[
{ name: 'Charlie', age: 20 },
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
]
How to sort an array of objects by property values ?
In this article, we will try to understand how to sort an array of objects by property values in JavaScript with the help of certain examples.
Pre-requisite: Array of Objects in JavaScript
Example:
Input:
[
{ name: "Ram", age: 17 },
{ name: "Mohan", age: 30 },
{ name: "Shyam", age: 15 },
{ name: "Shyam", age: 17 },
]
Output:
[
{ name: 'Shyam', age: 15 },
{ name: 'Ram', age: 17 },
{ name: 'Shyam', age: 17 },
{ name: 'Mohan', age: 30 }
]
Explanation:
- Pick any property and sort the object on the basis of that property’s values in other objects inside an array of objects.
There are several methods that can be used to sort an array of objects by property values
Table of Content
- Using sort() with compare function
- Using sort() method
- Using localeCompare() for string values
- Using external libraries like Lodash