How to search the max value of an attribute in an array object ?
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 is by using the Math.max.apply() method.
Example 1: In this example, the array is traversed and the required values of the object are compared for each index of the array.
// Array of object var 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){ var maxValue = Number.MIN_VALUE; for ( var i=0;i<arr.length;i++){ if (arr[i].a>maxValue){ maxValue = arr[i].a; } } return maxValue; } var maxValue = fun(arr); console.log(maxValue); |
chevron_right
filter_none
Output:
50
Example 2: In this example, we find the max value of an attribute by using Math.max.apply() function. It has two parameters:
- this
- array-like object
Syntax:
Math.max.apply(thisArg, [ argsArray])
More information can be found at https://developer.mozilla.org/
var arr = [ { a: 10, b: 25 }, { a: 30, b: 5 }, { a: 20, b: 15 }, { a: 50, b: 35 }, { a: 40, b: 45 }, ]; var maxValue = Math.max.apply( null , arr.map( function (o) { return o.a; })); console.log(maxValue); |
chevron_right
filter_none
Output:
50