Skip to content

JavaScript array min value | Example code

  • by

Use Math.min() function to get the minimum valued number passed into it, or NaN if any parameter isn’t a number and can’t be converted into one.

Buy functions min accept only number arguments. You have to use spread operator (…), apply() or reduce() with math.

JavaScript array min value Example

HTML example code:

Since Math.min() expect the numbers as arguments, and not an array.

Math.min(6, 3, 5, 2, 9)

Math.min() with spread operator (…)

These built-in Math functions, will work with array.

<!DOCTYPE html> 
<html> 

<body> 
	<script> 

		var arr = [ 6, 3, 5, 2, 9 ];
		var min = Math.min(...arr) 
		console.log(min);

	</script> 
</body> 

</html> 

apply()

Calling the function Function.prototype.apply() will have the same effect as the spread syntax:

<script> 
		var arr = [ 6, 3, 5, 2, 9 ];
		var min = Math.min.apply(null, arr);
		console.log(min);

</script> 

Sorting Array

The code sort((a,b) => a-b) will sort numbers in ascending order from smallest to largest.

<script> 
		var arr = [ 6, 3, 5, 2, 9 ];
		arr.sort((a,b) => a-b);
		const min = arr[0];
		console.log(min);

</script>

Using a for loop or .reduce()

You can use for loop to find the minimum numbers in an array:

<script> 
		var arr = [ 6, 3, 5, 2, 9 ];
		let min = arr[0];

		for (let i = 1; i < arr.length; i++) {
			let value = arr[i]
			min = (value < min) ? value : min
		}

		console.log(min);
		
</script> 

Using Reduce method

<script> 

		var arr = [ 6, 3, 5, 2, 9 ];
		const minUsingReduce = () => arr.reduce((min, currentValue) => Math.min(min, currentValue), arr[0])

		console.log(minUsingReduce());

</script> 

Output: Minimum value will be same for all example because Array have same values.

JavaScript array min value

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

Discover more from Tutorial

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

Continue reading