Computer >> Computer tutorials >  >> Programming >> Javascript

Removing Negatives from Array in JavaScript


Given an array arr of multiple values. For example −

[-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.

Therefore, let’s write the code for this function −

Example

The code for this will be −

// 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

The output in the console will be −

[ 1, 8, 9 ]