How to use Lodash _.sortBy() method In Javascript
In this approach, we are using third party librray that is lodash. lodash provides methods for arrays and objects here we are using _.sortBy() method that sort the arrays of object in ascending order. we will get our sorted array of objects by using this method after that we can directlly access the last element if that array as it will be the maximum.
Example: This example shows the implementation of the above-explained approach.
// Array of object
let arr = [
{
a: 10,
b: 25
},
{
a: 30,
b: 5
},
{
a: 20,
b: 15
},
{
a: 50,
b: 35
},
{
a: 40,
b: 45
},
];
// Returns max value of
// attribute 'a' in array
const _ = require("lodash");
// Use of _.sortBy() method
let sorted_obj = _.sortBy(arr,
[function (o) { return o.a; }]);
// Printing the output
console.log(sorted_obj[sorted_obj.length-1]);
Output:
{ a: 50, b: 35 }
How to search the max value of an attribute in an array object ?
In this article, we will learn how to search for the maximum value of an attribute in an array object. The maximum value of an attribute in an array of objects can be searched in two ways, one by traversing the array and the other method by using the Math.max.apply() method.
These are the following methods:
Table of Content
- Using Loop
- Using Math.max.apply()
- Using reduce() method
- Using Lodash _.sortBy() method
- Using Array.prototype.sort()