
- 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
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 ]
- Related Questions & Answers
- Removing Negatives from Array in JavaScript
- Removing redundant elements from array altogether - JavaScript
- Removing duplicate objects from array in JavaScript
- Removing all the empty indices from array in JavaScript
- Removing an element from an Array in Javascript
- Removing comments from array of string in JavaScript
- Removing an element from the end of the array in Javascript
- Removing an element from the start of the array in javascript
- Completely removing duplicate items from an array in JavaScript
- Removing an element from a given position of the array in Javascript
- Removing duplicates from a sorted array of literals in JavaScript
- Removing consecutive duplicates from strings in an array using JavaScript
- Removing item from array in MongoDB?
- Removing the odd occurrence of any number/element from an array in JavaScript
- Removing identical entries from an array keeping its length same - JavaScript
Advertisements