JavaScript get max value in Array of objects | Example code

Use inbuilt method Math apply(), map(), reduce() to get the max value in Array of objects in JavaScript. The Array object lets you store multiple values in a single variable.

Ways to get max value in Array of objects:-

  • Using apply() and map() method
  • array.reduce() method
  • Using map(), Math, and the spread operator

JavaScript get max value in an array of objects Example code

Let’s see HTML example code with different ways:-

Using apply() and map() method

Program of gets the maximum value of y property by using apply() and map() method.

<!DOCTYPE HTML> 
<html> 
	
	<body> 
		
		<script> 
			
			var array = [ 
				{ "x": "3/10/2020", "y": 0.02352007 }, 
				{ "x": "8/12/2021", "y": 0.0254234 }, 
				{ "x": "1/16/2010", "y": 0.02433546 }, 
				{ "x": "8/19/2015", "y": 0.0313423457 }]; 
				
			console.log(JSON.stringify(array)); 

			var res = Math.max.apply(Math, array.map(function(o) { 
					return o.y; }));
			
			console.log("Maximum value of y = " + res); 
				 
		</script> 
	</body> 
</html>	

Using reduce()

Example code of how to gets the maximum value of y property by using reduce() method. It returns the whole object.

<script> 
			
			var array = [ 
				{ "x": "3/10/2020", "y": 0.02352007 }, 
				{ "x": "8/12/2021", "y": 0.0254234 }, 
				{ "x": "1/16/2010", "y": 0.02433546 }, 
				{ "x": "8/19/2015", "y": 0.0313423457 }]; 
				
			console.log(JSON.stringify(array)); 

			var res = JSON.stringify(array.reduce(function(prev, current) { 
                    return (prev.y > current.y) ? prev : current  }));
			
			console.log("Maximum value of y = " + res); 
				 
</script> 

Using map(), Math, and the spread operator

Created a function to get max and min from Array.

<script> 

		var data = [ 
		{ "x": "3/10/2020", "y": 0.02352007 }, 
		{ "x": "8/12/2021", "y": 0.0254234 }, 
		{ "x": "1/16/2010", "y": 0.02433546 }, 
		{ "x": "8/19/2015", "y": 0.0313423457 }]; 

		console.log(JSON.stringify(data)); 

		function getYs(){
			return data.map(d => d.y);
		}
		function getMinY(){
			return Math.min(...getYs());
		}
		function getMaxY(){
			return Math.max(...getYs());
		}

		var res = getMaxY();
		
		console.log("Maximum value of y = " + res); 

</script>

Output: Result will same for all code because given Array values is same.

JavaScript get max value in Array of objects

Do comment if you have any doubts and suggestions on this JS Array topic.

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.