I am having a hard time wrapping my brain around this one :/
- (Removing Negatives) Given an array X of multiple values (e.g. [-3,5,1,3,2,10]), write a program that removes any negative values in the array. Once your program is done X should be composed of just positive numbers. Do this without creating a temporary array and only using pop method to remove any values in the array.
My thought was to write a loop through the array. If X[i] is negative, start another loop swapping X[j] and X[j+1] until the end of the array. (to preserve the order of the array) then use pop().
When I run the script it looks like the loop is infinite. Also it looks like if there are two negative values in a row the second one may get skipped in the next iteration of i. Is there a simpler way?
var X = [1,-6,-7,8,9];
//test= [1,-7,8,-6,9]
temp = 0
for (i = 0;i<X.length-1;i++){
if (X[i]<0){
for (j = i;j<=X.length-1;j++){
X[j] = temp
X[j] = X[j+1]
X[j+1] = temp
}
if(X[X.length-1] < 0){X.pop()}
}
};
console.log(X);
Array.splice?X[j+1] = tempinside yourjloop. Whenjis equal toX.length - 1, this line will add an additional entry into the array, causing it to loop again, again adding and looping and adding... forever