JavaScript map max value | Example code

Use spread the values() into Math.max to get max map in JavaScript.

JavaScript map max value Example

HTML example code: Use spread the values() into Math.max:

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		let m = new Map([['a', 2], ['b',4], ['c',6]])

		console.log("Max:", Math.max(...m.values()))

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

Output:

JavaScript map max value

Another Example

If you need both the key and value, then use reduce() using the entries() method for the map:

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		let m = new Map([['a', 2], ['b',4], ['c',6]])

		console.log([...m.entries()].reduce((a, e ) => e[1] > a[1] ? e : a))

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

Output: Array [ “c”, 6 ]

Q: How to find the max id in an array of objects in JavaScript?

Answer: Get the max value from Object Array, in this example will get by name attribute.

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		const data = [
		{id: 1, name: "A"},
		{id: 2, name: "B"},
		{id: 3, name: "C"},
		{id: 4, name: "D"},
		{id: 5, name: "E"},
		{id: 6, name: "F"}];

		var max = data.reduce((acc, data) => acc = acc > data.name ? acc : data.name, 0);

		console.log(max);

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

Output: F

Find max of array of objects key using math apply method:

<!DOCTYPE HTML> 
<html> 

<body> 

	<script> 

		const data = [
		{id: 1, name: 101},
		{id: 2, name: 202},
		{id: 3, name: 303},
		{id: 4, name: 405},
		{id: 5, name: 505},
		{id: 6, name: 606}];

		var max = Math.max.apply(Math, data.map(function(o) { 
			return o.name; }));

		console.log(max);

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

Output: 606

Do comment if you have any doubts and suggestions on this program code/

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.