Skip to content

JavaScript get max value in Array of objects | Examples code

  • by

There are many ways to get the max value in an array of objects in JavaScript. Like we can use loop through all values and compare them to the maximum value or sort the array or use Math. max.

For example, Array looks like this:

var myArray = [
        {"ID": 1, "Rate": 1200},
        {"ID": 2, "Rate": 1000},
        {"ID": 3, "Rate": 3000},
        {"ID": 4, "Rate": 6000}
        ]

Examples of JavaScript get max value in Array of objects

HTML example code.

Example 1

One way is to loop through all elements and compare them to the highest value.

<!DOCTYPE html>
<html>
<head>

    <script>
        var myArray = [
        {"ID": 1, "Rate": 1200},
        {"ID": 2, "Rate": 1000},
        {"ID": 3, "Rate": 3000},
        {"ID": 4, "Rate": 6000}
        ]

        var high = Number.NEGATIVE_INFINITY;
        
        var tmp;
        for (var i=myArray.length-1; i>=0; i--) {
            tmp = myArray[i].Rate;
            if (tmp > high) high = tmp;
        }
        alert(high);
    </script>
</head>
<body>

</body>
</html>

Output:

JavaScript get max value in Array of objects

Example 2

<!DOCTYPE html>
<html>
<head>

    <script>
        var myArray = [
        {"ID": 1, "Rate": 1200},
        {"ID": 2, "Rate": 1000},
        {"ID": 3, "Rate": 3000},
        {"ID": 4, "Rate": 6000}
        ]

        const minmax = (someArrayOfObjects, someKey) => {
          const values = someArrayOfObjects.map( value => value[someKey] );
          return {
              max: Math.max.apply(null, values) 
          };
      };


      console.log(minmax(myArray, 'Rate'));
  </script>
</head>
<body>

</body>
</html>

Output: Object { max: 6000 }

Example 3: sort()

First sort the JS array with a custom sorting function:

var sorted = persons.sort(function(a, b) {
  if(a.Age > b.Age) return 1;
  else if(a.Age < b.Age) return -1;
  else return 0;
});

Then take the first is “Minimum” and last is “Maximum”:

var min = sorted[0],
    max = sorted[sorted.length - 1];

Do comment if you have another way to it or have any suggestions.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading