How to use Loop In Javascript
In this approach, the array is traversed and the required values of the object are compared for each index of the array.
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
function fun(arr) {
let maxValue = Number.MIN_VALUE;
for (let i = 0; i < arr.length; i++) {
if (arr[i].a > maxValue) {
maxValue = arr[i].a;
}
}
return maxValue;
}
let maxValue = fun(arr);
console.log(maxValue);
Output
50
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()