
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
- Related Questions & Answers
- JavaScript Algorithm - Removing Negatives from the Array
- Removing duplicate objects from array in JavaScript
- Removing redundant elements from array altogether - JavaScript
- Removing an element from an Array in Javascript
- Removing comments from array of string in JavaScript
- Completely removing duplicate items from an array in JavaScript
- Removing all the empty indices from array in JavaScript
- Removing item from array in MongoDB?
- Removing duplicates from a sorted array of literals in JavaScript
- Removing consecutive duplicates from strings in an array using JavaScript
- Removing an element from the end of the array in Javascript
- Removing an element from the start of the array in javascript
- Removing parentheses from mathematical expressions in JavaScript
- Count groups of negatives numbers in JavaScript
- Removing identical entries from an array keeping its length same - JavaScript
Advertisements