Skip to content
Related Articles
Open in App
Not now

Related Articles

How to search the max value of an attribute in an array object ?

Improve Article
Save Article
  • Last Updated : 15 Dec, 2022
Improve Article
Save Article

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.

Example 1: In this example, the array is traversed and the required values of the object are compared for each index of the array.

javascript




<script>
    // 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);
</script>

Output:

50

Example 2: In this example, we find the max value of an attribute by using Math.max.apply() function. 

Syntax:

Math.max.apply(thisArg, [ argsArray])

Parameters: It has two parameters:

  • thisArg: This argument is used to provide value for the call to the function.
  • argsArray: It is an optional parameter. This is an array object used for specifying arguments with which function should be called.

javascript




<script>
    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);
</script>

Output:

50

Example 3: In this example, we will use reduce() method with which all the values will be compared, and then, at last, the final value will be stored which further will be stored in a variable that will be output over the console.

Javascript




<script>
    let array = [
      { a: 1, b: 2 },
      { a: 2, b: 4 },
      { a: 3, b: 6 },
      { a: 4, b: 8 },
      { a: 5, b: 10 },
      { a: 6, b: 12 },
    ];
     
    let maxValue = array.reduce((acc, value) => {
      return (acc = acc > value.b ? acc : value.b);
    }, 0);
     
    console.log(maxValue);
</script>

Output:

 12

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!