Get the smallest positive number JavaScript | Array example code

There are many ways to Get the smallest positive number in JavaScript.

  • Remove negative value from an array and arrange positive value in ascending order and get first value form array.
  • Remove negative value from an array and use Math.min() to get smallest positive number in Array.

Example Find the smallest positive number JavaScript

HTML example code

Ascending order

Using if condition statement and for-loop.

<!DOCTYPE html>
<html>
<body>

  <script>
    var myArray = [7, -2, 3, 4, 5, -1, 6];
    for (i=0;i<myArray.length;i++) 
    {
     if (myArray[i]<0)
      myArray.splice(i, 1);
  }
  myArray.sort();

  console.log(myArray);
  console.log("Min Positive value : "+ myArray[0])
</script>

</body>
</html>

Output:

Get the smallest positive number JavaScript

Exampe Get only positive numbers from array JS math.min

<!DOCTYPE html>
<html>
<body>

  <script>
    var myArray = [7, -2, 3, 4, 5, -1, 6];
    for (i=0;i<myArray.length;i++) 
    {
     if (myArray[i]<0)
      myArray.splice(i, 1);
  }

  console.log(Math.min(...myArray));
  
</script>

</body>
</html>

Output: 3

Do comment if you have any doubts and suggestions on this JS 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.