Skip to content

Find the smallest number in array JavaScript | Different methods examples

  • by

There are several built-in ways to find the smallest number in Array JavaScript. Some methods are using the Math functions with the spread operator (…) and sorting the array numerically with .sort().

Different methods of finding the minimum JS Array:-

  • Math functions
    • Math.min() – spread operator (…)
    • Math.min.apply() – (Without the spread operator)
  • Using a for loop or .reduce()

Find the smallest number in array JavaScript Example

Let’s see all ways to do it in HTML with examples code:

Math.min() – spread operator (…)

The tersest expressive code to find the minimum value is probably rest parameters:

<!DOCTYPE html>
<html>
<body>
	
	<script>
		const arr = [4, 8, 0, 7, 6, 2, 5, 9];
		const min = Math.min(...arr);
		console.log(min)
	</script>

</body>
</html>

Math.min.apply() – (Without the spread operator)

Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don’t need to change the function’s context:

<script>
		const arr = [4, 8, 0, 7, 6, 2, 5, 9];
		var min = Math.min.apply(Math, arr)
		console.log(min)
</script>

Using a for loop or .reduce()

User case for Array.prototype.reduce:

<script>
		const arr = [4, 8, 0, 7, 6, 2, 5, 9];
		const min = arr.reduce((a, b) => Math.min(a, b))
		console.log(min)
	</script>

Output: The result will be the same for all examples because input array values are the same.

Find the smallest number in array JavaScript

Source: https://stackoverflow.com/

Using a for loop

<!DOCTYPE html>
<html>
<body>
	
	<script>
		var arr = [5,1,9,5,7];
		var smallest = arr[0];

		for(var i=1; i<arr.length; i++){
			if(arr[i] < smallest){
				smallest = arr[i];   
			}
		}

		console.log(smallest);
	</script>

</body>
</html>

Output: 1

Do comment if you have any problems 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

Discover more from Tutorial

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

Continue reading