Skip to content

JavaScript find min value in an array of objects | Example code

  • by

Use JavaScript reduce() or Math method to get the min value in an array of objects. Using the Math functions with the spread operator (…) and sorting the array numerically with .sort() is a way to get the min value-form an array.

JavaScript find min value in an array of objects Examples

HTML example codes:-

Using apply() and map() method

Program of gets the minimum 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.min.apply(Math, array.map(function(o) { 
			return o.y; }));

		console.log("Minimum value of y = " + res); 

	</script> 
</body> 
</html>	

Using reduce() Method

Example code for how to gets the minimum 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("Minimum value of y = " + res); 
		
	</script>

Using map(), Math, and the spread operator

You can create 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 = getMinY();
		
		console.log("Minimum value of y = " + res); 

</script> 

Output: Result will be same because Array object values are same.

JavaScript find min value in an array of objects

Do comment if you have any doubts and suggestions on this 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

Your email address will not be published. Required fields are marked *