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

Finding a smallest value in Array is easy using for loop statement. You need to first traversal array element and store it to new array (smallest_value_array). Compare the existing array value with new one before you storing 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.

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.

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: 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.