Skip to content

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 the first value from the array.
  • Remove negative value from an array and use Math.min() to get the smallest positive number in the 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

Example 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

Comment code

if (myAtrray[i] > 0 && myArray[i]< currentLowest ){
currentLowest = myArray[i]
}
[7, -2, 3, 4, 5, -1, 6].filter((x)=> x>0);
Result : [7, 3, 4, 5, 6]

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

5 thoughts on “Get the smallest positive number JavaScript | Array example code”

  1. Both solutions are poor in terms of efficiency. You can do that better simply by removing sort and adding inside your loop: if (myAtrray[i] > 0 && myArray[i]< currentLowest ){
    currentLowest = myArray[i]
    }

    Of course previously seting it currentLowest to some absurd number linke maximum number highest posible

  2. Ascending order example:
    “The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.”
    Ascending example does not work with above two digit numbers. It is very confusing for new players please nerf it. and suck on my ass

Leave a Reply

Discover more from Tutorial

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

Continue reading