Skip to content

Remove negative values from array in JavaScript | Example code

  • by

Write a function that removes any negative values in the array. In Function only uses a pop method to remove any values in the array.

<!DOCTYPE html>
<html>
<body>

  <script>
    function ra(x){

      while (x.length && x[x.length - 1] < 0) {
       x.pop();
     }
     for (var i = x.length - 1; i >= 0; i--) {
       if (x[i] < 0) {

        x[i] = x[x.length - 1];
        x.pop();
      }
    }
    return x;
  }

    var x = [7, -2, 3, 4, 5, -1, 6];
    console.log(ra(x));

  </script>

</body>
</html>

Output:

Remove negative values from array in JavaScript

Another example

<!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(myArray);

</script>

</body>
</html>

Practice Removing Negatives From Array

Sort the array first so the negative numbers are at the end. Sort with a callback that moves the negative numbers to the end.

Then iterate backward and remove the last indices with the pop method as long as they are negative. The array will be left with positive values.

<!DOCTYPE html>
<html>
<body>

  <script>
    var X = [-3, 5, 3, 8, 1,-6,-7,8,9];

    X.sort(function(a,b) {
      return b - a;
    });

    for (var i=X.length; i--;) {
      if ( X[i] < 0 ) X.pop();
    }

    console.log(X);
  </script>

</body>
</html>

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

Discover more from Tutorial

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

Continue reading