JavaScript Algorithm - Removing Negatives from the Array


Given an array X of multiple values (e.g. [-3,5,1,3,2,10]), We are required to write a function that removes any negative values in the array.

Once the function finishes its execution the array should be composed of just positive numbers. We are required to do this without creating a temporary array and only using pop method to remove any values in the array.

Example

Following is the code −

// strip all negatives off the end
while (x.length && x[x.length - 1] < 0) {
   x.pop();
}
for (var i = x.length - 1; i >= 0; i--) {
   if (x[i] < 0) {
      // replace this element with the last element (guaranteed to be positive)
      x[i] = x[x.length - 1];
      x.pop();
   }
}

Output

This will produce the following output on console −

[ 1, 8, 9 ]

Updated on: 01-Oct-2020

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements