Removing Negatives from Array in JavaScript

JavascriptWeb DevelopmentFront End Technology

The given task is to remove the negative values from the array.

Input-Output Scenario

Let’s look into input output scenarios. Consider there is an array and it is having both negative and positive integer values. We need to remove the negative values from the array and return the array.

Input = [-2, 5, -7, 32, 78, -32];
Output = [5, 32, 78]

Now let’s assume there are no negatives integer values in the array. so, the array will be returned in the same order.

Input = [56, 43, 12, 67, 69, 34];
Output = [56, 43, 12, 67, 69, 34]

Using the pop() method

The pop() method in JavaScript will remove the last element in the array and it changes or modifies the original array.


Following is the syntax of pop() method, There will be no parameters for this method.



In the following example, we have sorted in the descending order by using compare function. So that the negative numbers will be at last positions in the array. Then by using pop() method we have removed the last indices until the there are no more negative integers. Thus the array will have positive integers.

<!DOCTYPE html> <html> <head> <p id = "para"></p> </head> <body> <script> const array = [45, 23, 12, -4, 76, 56, 43, -9]; array.sort(function(a,b) { return b - a; }); let x = array.length for (x; x--;) { if ( array[x] < 0 ){ array.pop(); } } document.getElementById("para").innerHTML = "Array after removing negatives values from it:" + array; </script> </body> </html>

If we observe the following output, it returned the array by deleting the negative elements in the array in descending order −

Using the splice() method

The splice() method in JavaScript will add or remove the elements in an array and this method will change the original array.


Below is the syntax of splice() method,

array.splice(index, numofelements, item1, ....., itemN)


  • The first parameter(index) is for the position to add or delete the elements. And it is a mandatory parameter.

  • Second parameter is for number of elements to be removed. This is an optional parameter


In the example, we have declared an array with both negative and positive integers. Then we have iterated through the array elements by for loop and if there is any element which is less than 0, the splice method will remove that particular element.

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <button onClick = "func()"> Click to remove (-)'s </button> <p id = "para"></p> <script> function func() { const arr = [09, 38, 45, -25, 42, -12, 98]; let x = 0; for (x; x < arr.length; x++){ if (arr[x] < 0) arr.splice(x, 1); } document.getElementById("para").innerHTML = arr; } </script> </body> </html>

In the output, we can see that the negative elements have been removed with splice method and returned the array.

Updated on 22-Sep-2022 12:18:22