Skip to content

Find the smallest number in array JavaScript for loop | Example code

  • by

Finding the smallest value in Array is easy to use for loop statements. You need to first traversal the array element and store it to a new array (smallest_value_array). Compare the existing array value with a new one before you store it

Find the smallest number in array JavaScript for loop Example

HTML example code program:-

In the example we have given an array with values, now we created a new array “smallest” with initializing smallest as the first element. Go through each element of the array and compare it. If it’s smaller then stored one then replace it.

<!DOCTYPE html>
<html>
<body>
	
	<script>
		var arr = [4,1,9,5,0];
		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:

Find the smallest number in array JavaScript for loop

Another Simple way without for loop

Just sort the array in increasing order. The first element in sorted array would be two smallest elements.

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

		var smallest = arr.sort((a, b) => a - b);

		alert(smallest[0]);
	</script>

</body>
</html>

Output: 1

Note: By default, the sort method sorts elements alphabetically. To sort numerically just add a new method that handles numeric sorts

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

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